This commit is contained in:
xiangwbs
2017-11-22 22:36:00 +08:00
18 changed files with 246 additions and 181 deletions
@@ -0,0 +1,23 @@
package com.xwbing.exception;
/**
* 项目名称: boot-module-demo
* 创建时间: 2017/11/22 15:08
* 作者: xiangwb
* 说明: 工具类异常
*/
public class UtilException extends RuntimeException {
private static final long serialVersionUID = 3338405359271762532L;
public UtilException(Throwable cause) {
super(cause);
}
public UtilException(String message) {
super(message);
}
public UtilException(String message, Throwable cause) {
super(message, cause);
}
}
@@ -1,5 +1,6 @@
package com.xwbing.util;
import com.xwbing.exception.UtilException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -70,8 +71,7 @@ public class DateUtil2 {
LocalDateTime localDateTime;
Instant instant;
if (dateStr.length() < 10) {
logger.error("时间格式错误:" + dateStr);
throw new RuntimeException("时间格式错误:" + dateStr);
throw new UtilException("时间格式错误:" + dateStr);
}
if (dateStr.length() == 10) {
dateStr += " 00:00:00";
@@ -1,5 +1,6 @@
package com.xwbing.util;
import com.xwbing.exception.UtilException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -77,8 +78,7 @@ public class DecimalUtil {
*/
public static Double div(Double v1, Double v2, int scale) {
if (scale < 0){
LOGGER.error("小数位数不能为负数");
throw new IllegalArgumentException("小数位数不能为负数");
throw new UtilException("小数位数不能为负数");
}
BigDecimal b1 = new BigDecimal(v1.toString());
BigDecimal b2 = new BigDecimal(v2.toString());
@@ -1,6 +1,7 @@
package com.xwbing.util;
import com.xwbing.exception.UtilException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -52,7 +53,7 @@ public class Digests {
return result;
} catch (GeneralSecurityException e) {
LOGGER.error(e.getMessage());
throw new RuntimeException("加密失败");
throw new UtilException("加密失败");
}
}
@@ -63,7 +64,7 @@ public class Digests {
*/
public static byte[] generateSalt(int numBytes) {
if (numBytes <= 0) {
throw new RuntimeException("numBytes argument must be a positive integer (1 or larger)");
throw new UtilException("numBytes argument must be a positive integer (1 or larger)");
}
byte[] bytes = new byte[numBytes];
random.nextBytes(bytes);
@@ -97,7 +98,7 @@ public class Digests {
return messageDigest.digest();
} catch (Exception e) {
LOGGER.error(e.getMessage());
throw new RuntimeException(e);
throw new UtilException("加密失败");
}
}
}
@@ -2,7 +2,10 @@ package com.xwbing.util;
import com.xwbing.domain.entity.model.EmailModel;
import com.xwbing.exception.UtilException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.mail.*;
import javax.mail.internet.*;
@@ -14,6 +17,8 @@ import java.util.Properties;
* 说明: 邮箱工具类
*/
public class EmailUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(EmailUtil.class);
/**
* 发送邮件
*
@@ -22,16 +27,13 @@ public class EmailUtil {
*/
public static boolean sendTextEmail(EmailModel emailModel) {
try {
boolean result = true;
// 1. 创建参数配置, 用于连接邮件服务器的参数配置
Properties props = new Properties();// 用于连接邮件服务器的参数配置(发送邮件时才需要用到)
String serverHost = emailModel.getServerHost();// 设置发送邮件的邮件服务器的属性(这里使用网易的smtp服务器)
if (StringUtils.isEmpty(serverHost)) {
result = false;
throw new RuntimeException("发送邮件主机不能为空");
throw new UtilException("发送邮件主机不能为空");
}
props.setProperty("mail.transport.protocol",
emailModel.getProtocol());// 使用的协议(JavaMail规范要求)
props.setProperty("mail.transport.protocol", emailModel.getProtocol());// 使用的协议(JavaMail规范要求)
props.setProperty("mail.smtp.host", serverHost); // 发件人的邮箱的
// SMTP服务器地址
if (emailModel.getServerPort() != null) {
@@ -46,17 +48,14 @@ public class EmailUtil {
// From: 发件人
String fromEmail = emailModel.getFromEmail();
if (StringUtils.isEmpty(fromEmail)) {
result = false;
throw new RuntimeException("发送邮箱不能为空");
throw new UtilException("发送邮箱不能为空");
}
message.setFrom(new InternetAddress(emailModel.getFromEmail()));
// To: 收件人
if (StringUtils.isEmpty(emailModel.getToEmail())) {
result = false;
throw new RuntimeException("接收邮箱不能为空");
throw new UtilException("接收邮箱不能为空");
}
InternetAddress[] toEmailList = InternetAddress.parse(emailModel
.getToEmail());// toEmail格式为"aaa,bbb,..."或"aaa"
InternetAddress[] toEmailList = InternetAddress.parse(emailModel.getToEmail());// toEmail格式为"aaa,bbb,..."或"aaa"
message.setRecipients(Message.RecipientType.TO, toEmailList);
/*
* message.addRecipient(MimeMessage.RecipientType.TO,new
@@ -68,8 +67,7 @@ public class EmailUtil {
*/
// Subject: 邮件主题
if (StringUtils.isEmpty(emailModel.getSubject())) {
result = false;
throw new RuntimeException("邮件主题不能为空");
throw new UtilException("邮件主题不能为空");
}
message.setSubject(emailModel.getSubject());
// 向multipart对象中添加邮件的各个部分内容,包括文本内容和附件
@@ -86,8 +84,7 @@ public class EmailUtil {
Transport transport = session.getTransport("smtp");
// 5. 使用 邮箱账号 和 密码 连接邮件服务器
if (StringUtils.isEmpty(emailModel.getPassword())) {
result = false;
throw new RuntimeException("发送邮箱密码不能为空");
throw new UtilException("发送邮箱密码不能为空");
}
transport.connect(serverHost, fromEmail, emailModel.getPassword());// 这里认证的邮箱必须与
// message中的发件人邮箱一致,否则报错
@@ -96,13 +93,10 @@ public class EmailUtil {
transport.sendMessage(message, message.getAllRecipients());
// 7. 关闭连接
transport.close();
return result;
} catch (AddressException e) {
e.printStackTrace();
return false;
return true;
} catch (MessagingException e) {
e.printStackTrace();
return false;
LOGGER.error(e.getMessage());
throw new UtilException("发送邮件失败");
}
}
@@ -4,6 +4,8 @@ import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.StringEscapeUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
@@ -16,6 +18,7 @@ import java.net.URLEncoder;
*/
public class EncodeUtils {
private static final String DEFAULT_URL_ENCODING = "UTF-8";
private static final Logger LOGGER = LoggerFactory.getLogger(EncodeUtils.class);
/**
* Hex编码.
@@ -31,7 +34,8 @@ public class EncodeUtils {
try {
return Hex.decodeHex(input.toCharArray());
} catch (DecoderException e) {
throw new IllegalStateException("Hex Decoder exception", e);
LOGGER.error(e.getMessage());
throw new IllegalStateException("Hex Decoder exception");
}
}
@@ -63,7 +67,7 @@ public class EncodeUtils {
*/
public static byte[] base64Decode(String input) {
return Base64.decodeBase64(input);
/*
/*
* java8新特性
*/
// return java.util.Base64.getDecoder().decode(input);
@@ -76,7 +80,8 @@ public class EncodeUtils {
try {
return URLEncoder.encode(input, DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("Unsupported Encoding Exception", e);
LOGGER.error(e.getMessage());
throw new IllegalArgumentException("Unsupported Encoding Exception");
}
}
@@ -87,7 +92,8 @@ public class EncodeUtils {
try {
return URLDecoder.decode(input, DEFAULT_URL_ENCODING);
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException("Unsupported Encoding Exception", e);
LOGGER.error(e.getMessage());
throw new IllegalArgumentException("Unsupported Encoding Exception");
}
}
@@ -1,10 +1,13 @@
package com.xwbing.util;
import com.xwbing.exception.UtilException;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.io.FilenameUtils;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.File;
import java.io.FileInputStream;
@@ -37,6 +40,7 @@ public class ExcelUtil {
* 分隔符
*/
public final static String SEPARATOR = ";";
private static final Logger LOGGER = LoggerFactory.getLogger(ExcelUtil.class);
/**
* 获取工作簿
@@ -45,9 +49,8 @@ public class ExcelUtil {
* @param columns
* @param list
* @return
* @throws Exception
*/
public static HSSFWorkbook Export(String title, String[] columns, List<String[]> list) throws Exception {
public static HSSFWorkbook Export(String title, String[] columns, List<String[]> list) {
// 声明一个工作薄
HSSFWorkbook wb = new HSSFWorkbook();
// 声明一个单子并命名
@@ -115,10 +118,10 @@ public class ExcelUtil {
try {
getMethod = classOfT.getMethod(getMethodStr.toString());
} catch (NoSuchMethodException e1) {
System.out.println("NoSuchMethodException");
LOGGER.error(e1.getMessage());
continue;
} catch (SecurityException e1) {
System.out.println("SecurityException");
LOGGER.error(e1.getMessage());
continue;
}
// 执行get方法
@@ -127,7 +130,7 @@ public class ExcelUtil {
value = Objects.equals("null", value) ? null : value;
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
LOGGER.error(e.getMessage());
}
temp[i] = value;
}
@@ -198,17 +201,16 @@ public class ExcelUtil {
System.out.println("Exception" + e);
continue;
}
}
}
resultList.add(obj);
}
}
return resultList;
} catch (IOException e) {
e.printStackTrace();
LOGGER.error(e.getMessage());
throw new UtilException("excel文件生成类失败");
}
return resultList;
}
/**
@@ -247,7 +249,6 @@ public class ExcelUtil {
* @param workbook
* @param sheetNum
* @return
* @throws IOException
*/
private static List<String> exportListFromExcel(Workbook workbook, int sheetNum) {
Sheet sheet = workbook.getSheetAt(sheetNum);
@@ -1,6 +1,7 @@
package com.xwbing.util;
import com.alibaba.fastjson.JSONObject;
import com.xwbing.exception.UtilException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.*;
import org.apache.http.client.HttpRequestRetryHandler;
@@ -35,7 +36,7 @@ import java.util.concurrent.TimeUnit;
* 说明: HttpClientUtil
*/
public class HttpClientUtil {
private static Logger logger = LoggerFactory.getLogger(HttpClientUtil.class);
private static Logger LOGGER = LoggerFactory.getLogger(HttpClientUtil.class);
private static PoolingHttpClientConnectionManager poolingHttpClientConnectionManager;
private static final String APPLICATION_JSON = "application/json";
private static final String URL_ERROR = "Request Url can not be empty";
@@ -55,7 +56,7 @@ public class HttpClientUtil {
private static final RequestConfig defaultRequestConfig = RequestConfig.custom().setSocketTimeout(600000).setConnectTimeout(600000).build();
// Request retry handler
private static HttpRequestRetryHandler retryHandler = (exception, executionCount, context) -> {
logger.info("retryRequest-->");
LOGGER.info("retryRequest-->");
if (executionCount > 5) {
return false;
}
@@ -98,7 +99,7 @@ public class HttpClientUtil {
if (param == null) {
throw new IllegalArgumentException(PARAM_ERROR);
}
logger.info("postByJson request URL:{}==================", url);
LOGGER.info("postByJson request URL:{}==================", url);
HttpPost post = new HttpPost(url);// 创建HttpPost的实例
post.setEntity(new StringEntity(param.toString(), "UTF-8"));// 设置参数到请求对象中
post.addHeader("Content-Type", APPLICATION_JSON);// 发送json数据需要设置contentType
@@ -119,7 +120,7 @@ public class HttpClientUtil {
if (param == null || param.size() == 0) {
throw new IllegalArgumentException(PARAM_ERROR);
}
logger.info("postByForm request URL:{}================", url);
LOGGER.info("postByForm request URL:{}================", url);
HttpPost post = new HttpPost(url);
// 创建参数队列
List<NameValuePair> params = new ArrayList<>();
@@ -129,8 +130,8 @@ public class HttpClientUtil {
try {
post.setEntity(new UrlEncodedFormEntity(params, "UTF-8"));
} catch (UnsupportedEncodingException e) {
logger.error(e.getMessage());
throw new RuntimeException("postByForm数据转换错误");
LOGGER.error(e.getMessage());
throw new UtilException("postByForm数据转换错误");
}
return getResult(post);
}
@@ -145,7 +146,7 @@ public class HttpClientUtil {
if (StringUtils.isEmpty(url)) {
throw new IllegalArgumentException(URL_ERROR);
}
logger.info("GET request URL:{}======================", url);
LOGGER.info("GET request URL:{}======================", url);
HttpGet httpGet = new HttpGet(url);
return getResult(httpGet);
}
@@ -164,7 +165,7 @@ public class HttpClientUtil {
if (param == null || param.size() == 0) {
throw new IllegalArgumentException(PARAM_ERROR);
}
logger.info("PUT request URL:{}====================", url);
LOGGER.info("PUT request URL:{}====================", url);
HttpPut put = new HttpPut(url);
put.setEntity(new StringEntity(param.toString(), "UTF-8"));
put.addHeader("Content-type", APPLICATION_JSON);
@@ -181,7 +182,7 @@ public class HttpClientUtil {
if (StringUtils.isBlank(url)) {
throw new IllegalArgumentException(URL_ERROR);
}
logger.info("delete request URL:{}=====================", url);
LOGGER.info("delete request URL:{}=====================", url);
HttpDelete delete = new HttpDelete(url);
return getResult(delete);
}
@@ -200,7 +201,7 @@ public class HttpClientUtil {
CloseableHttpResponse response = client.execute(request);
long end = System.currentTimeMillis();
long ms = end - start;
logger.info("网络接口请求时间为{} ms=======================", ms);
LOGGER.info("网络接口请求时间为{} ms=======================", ms);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {// 判断网络连接状态码是否正常(0-200都数正常)
HttpEntity entity = response.getEntity();// 获取结果实体
if (entity != null) {
@@ -213,8 +214,8 @@ public class HttpClientUtil {
} catch (IOException e) {
// result.setSuccess(false);
// result.setMsg(e.getMessage());
logger.error(e.getMessage());
throw new RuntimeException("请求网络接口错误");
LOGGER.error(e.getMessage());
throw new UtilException("请求网络接口错误");
} finally {
poolingHttpClientConnectionManager.closeExpiredConnections();
poolingHttpClientConnectionManager.closeIdleConnections(120, TimeUnit.MILLISECONDS);
@@ -1,5 +1,9 @@
package com.xwbing.util;
import com.xwbing.exception.UtilException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
@@ -11,6 +15,8 @@ import java.net.UnknownHostException;
* 说明:
*/
public class IpUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(IpUtil.class);
public static String getIpAddr(HttpServletRequest request) {
// 获取X-Forwarded-For
String ip = request.getHeader("x-forwarded-for");
@@ -35,7 +41,8 @@ public class IpUtil {
try {
inet = InetAddress.getLocalHost();
} catch (UnknownHostException e) {
e.printStackTrace();
LOGGER.error(e.getMessage());
throw new UtilException("ip地址异常");
}
ip = inet.getHostAddress();
}
@@ -1,7 +1,10 @@
package com.xwbing.util;
import com.alibaba.fastjson.JSONObject;
import com.xwbing.exception.UtilException;
import org.apache.commons.beanutils.PropertyUtilsBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.beans.PropertyDescriptor;
import java.util.ArrayList;
@@ -15,6 +18,8 @@ import java.util.Map;
* 作者: xiangwb
*/
public class JSONUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(JSONUtil.class);
/**
* 实体对象不序列化转换成jsonobject
*
@@ -50,7 +55,8 @@ public class JSONUtil {
}
}
} catch (Exception e) {
e.printStackTrace();
LOGGER.error(e.getMessage());
throw new UtilException("不序列化对象转换错误");
}
return new JSONObject(params);
}
@@ -1,5 +1,9 @@
package com.xwbing.util;
import com.xwbing.exception.UtilException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
@@ -15,6 +19,8 @@ import java.util.Map;
* 文档: http://www.kdniao.com/documents
*/
public class KdniaoUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(KdniaoUtil.class);
/**
* 向指定 URL 发送POST方法的请求
*
@@ -66,7 +72,8 @@ public class KdniaoUtil {
result.append(line);
}
} catch (Exception e) {
e.printStackTrace();
LOGGER.error(e.getMessage());
throw new UtilException("快递鸟接口请求失败");
}
// 使用finally块来关闭输出流、输入流
finally {
@@ -88,10 +95,14 @@ public class KdniaoUtil {
* @param str 内容
* @param charset 编码方式
* @return
* @throws UnsupportedEncodingException
*/
public static String urlEncoder(String str, String charset) throws UnsupportedEncodingException {
return URLEncoder.encode(str, charset);
public static String urlEncoder(String str, String charset) {
try {
return URLEncoder.encode(str, charset);
} catch (UnsupportedEncodingException e) {
LOGGER.error(e.getMessage());
throw new UtilException("urlEncoder失败");
}
}
/**
@@ -103,11 +114,16 @@ public class KdniaoUtil {
* @return DataSign签名
* @throws Exception
*/
public static String encrypt(String content, String keyValue, String charset) throws Exception {
if (keyValue != null) {
return base64(MD5(content + keyValue, charset), charset);
public static String encrypt(String content, String keyValue, String charset) {
try {
if (keyValue != null) {
return base64(MD5(content + keyValue, charset), charset);
}
return base64(MD5(content, charset), charset);
} catch (Exception e) {
LOGGER.error(e.getMessage());
throw new UtilException("快递鸟签名出错");
}
return base64(MD5(content, charset), charset);
}
private static char[] base64EncodeChars = new char[]{'A', 'B', 'C', 'D',
@@ -122,21 +138,25 @@ public class KdniaoUtil {
*
* @param str 内容
* @param charset 编码方式
* @throws Exception
*/
private static String MD5(String str, String charset) throws Exception {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes(charset));
byte[] result = md.digest();
StringBuilder sb = new StringBuilder(32);
for (byte aResult : result) {
int val = aResult & 0xff;
if (val <= 0xf) {
sb.append("0");
private static String MD5(String str, String charset) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(str.getBytes(charset));
byte[] result = md.digest();
StringBuilder sb = new StringBuilder(32);
for (byte aResult : result) {
int val = aResult & 0xff;
if (val <= 0xf) {
sb.append("0");
}
sb.append(Integer.toHexString(val));
}
sb.append(Integer.toHexString(val));
return sb.toString().toLowerCase();
} catch (Exception e) {
LOGGER.error(e.getMessage());
throw new UtilException("快递鸟加密出错");
}
return sb.toString().toLowerCase();
}
/**
@@ -144,10 +164,14 @@ public class KdniaoUtil {
*
* @param str 内容
* @param charset 编码方式
* @throws UnsupportedEncodingException
*/
private static String base64(String str, String charset) throws UnsupportedEncodingException {
return base64Encode(str.getBytes(charset));
private static String base64(String str, String charset) {
try {
return base64Encode(str.getBytes(charset));
} catch (UnsupportedEncodingException e) {
LOGGER.error(e.getMessage());
throw new UtilException("快递鸟编码出错");
}
}
private static String base64Encode(byte[] data) {
@@ -1,6 +1,10 @@
package com.xwbing.util;
import com.xwbing.exception.UtilException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
@@ -15,6 +19,8 @@ import java.util.regex.Pattern;
* 说明: PingUtil
*/
public class PingUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(PingUtil.class);
/**
* Jdk1.5的InetAddresss,代码简单
*
@@ -26,7 +32,8 @@ public class PingUtil {
try {
return InetAddress.getByName(ipAddress).isReachable(timeOut);// 当返回值是true时,说明host是可用的,false则不可。
} catch (IOException e) {
throw new RuntimeException("无法连接该地址");
LOGGER.error(e.getMessage());
throw new UtilException("无法连接该地址");
}
}
@@ -45,7 +52,8 @@ public class PingUtil {
System.out.println(line);
return true;
} catch (Exception ex) {
throw new RuntimeException("无法连接该地址");
LOGGER.error(ex.getMessage());
throw new UtilException("无法连接该地址");
}
}
@@ -77,7 +85,8 @@ public class PingUtil {
br.close();
return connectedCount == pingTimes;
} catch (Exception ex) {
throw new RuntimeException("无法连接该地址");
LOGGER.error(ex.getMessage());
throw new UtilException("无法连接该地址");
}
}
@@ -6,7 +6,10 @@ import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.xwbing.exception.UtilException;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.imageio.ImageIO;
import java.awt.*;
@@ -29,6 +32,7 @@ import java.util.Map;
*/
public class QRCodeUtils {
private static QRCodeUtils.Internal internal = new QRCodeUtils.Internal();
private static final Logger LOGGER = LoggerFactory.getLogger(QRCodeUtils.class);
/***
* 生成默认尺寸不带logo的二维码
@@ -55,7 +59,8 @@ public class QRCodeUtils {
internal._output = output;
internal.output(output, internal.createCode(text));
} catch (Exception e) {
e.printStackTrace();
LOGGER.error(e.getMessage());
throw new UtilException("生成自定义尺寸不带logo的二维码失败");
}
}
@@ -89,8 +94,8 @@ public class QRCodeUtils {
return internal.addMaterial(bitMatrix);
//internal.output(output, bitMatrix);
} catch (WriterException e) {
e.printStackTrace();
return null;
LOGGER.error(e.getMessage());
throw new UtilException("生成自定义尺寸带logo的二维码失败");
}
}
@@ -102,19 +107,23 @@ public class QRCodeUtils {
* @return
* @throws Exception
*/
public static String decode(File file) throws Exception {
if (file == null) {
return null;
public static String decode(File file) {
try {
if (file == null) {
return null;
}
MultiFormatReader formatReader = new MultiFormatReader();
BufferedImage image = ImageIO.read(file);
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
Hashtable<DecodeHintType, Object> hints = new Hashtable<>();
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
Result result = formatReader.decode(binaryBitmap, hints);
return result.getText();
} catch (Exception e) {
LOGGER.error(e.getMessage());
throw new UtilException("解析二维码图片失败");
}
MultiFormatReader formatReader = new MultiFormatReader();
BufferedImage image = ImageIO.read(file);
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(source));
Hashtable<DecodeHintType, Object> hints = new Hashtable<>();
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
Result result = formatReader.decode(binaryBitmap, hints);
return result.getText();
}
private static class Internal {
@@ -273,7 +282,7 @@ public class QRCodeUtils {
}
}
public static void main(String[] args) throws Exception {
public static void main(String[] args){
// String tomcatHome = System.getProperty("catalina.home");
// String name="QRcode";
// File output=new File(tomcatHome+File.separator+"file"+File.separator+name+".png");
@@ -1,7 +1,10 @@
package com.xwbing.util;
import com.xwbing.exception.UtilException;
import org.bouncycastle.asn1.ASN1Sequence;
import org.bouncycastle.asn1.pkcs.RSAPrivateKeyStructure;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
@@ -26,17 +29,16 @@ import java.security.spec.X509EncodedKeySpec;
* 说明:
*/
public class RSAUtil {
private static final Logger LOGGER = LoggerFactory.getLogger(RSAUtil.class);
/**
* 从文件中加载公钥 测试的时候使用
*
* @return
* @throws Exception
*/
public static RSAPublicKey loadPublicKey() throws Exception {
public static RSAPublicKey loadPublicKey() {
try {
String filePath = RSAUtil.class.getClassLoader()
.getResource("rsa_public_key.pem").getPath();
String filePath = RSAUtil.class.getClassLoader().getResource("rsa_public_key.pem").getPath();
InputStream in = new FileInputStream(filePath);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String readLine;
@@ -52,9 +54,8 @@ public class RSAUtil {
br.close();
return loadPublicKey(sb.toString());
} catch (IOException e) {
throw new Exception("公钥数据流读取错误");
} catch (NullPointerException e) {
throw new Exception("公钥输入流为空");
LOGGER.error(e.getMessage());
throw new UtilException("公钥数据流读取错误");
}
}
@@ -64,8 +65,7 @@ public class RSAUtil {
* @param publicKeyStr 公钥数据字符串
* @throws Exception 加载公钥时产生的异常
*/
public static RSAPublicKey loadPublicKey(String publicKeyStr)
throws Exception {
public static RSAPublicKey loadPublicKey(String publicKeyStr) {
try {
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] buffer = base64Decoder.decodeBuffer(publicKeyStr);
@@ -73,13 +73,14 @@ public class RSAUtil {
X509EncodedKeySpec keySpec = new X509EncodedKeySpec(buffer);
return (RSAPublicKey) keyFactory.generatePublic(keySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此算法");
LOGGER.error(e.getMessage());
throw new UtilException("无此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("公钥非法");
LOGGER.error(e.getMessage());
throw new UtilException("公钥非法");
} catch (IOException e) {
throw new Exception("公钥数据内容读取错误");
} catch (NullPointerException e) {
throw new Exception("公钥数据为空");
LOGGER.error(e.getMessage());
throw new UtilException("公钥数据内容读取错误");
}
}
@@ -87,12 +88,10 @@ public class RSAUtil {
* 从文件中加载私钥 测试的时候使用 私钥文件名
*
* @return 是否成功
* @throws Exception
*/
public static RSAPrivateKey loadPrivateKey() throws Exception {
public static RSAPrivateKey loadPrivateKey() {
try {
String filePath = RSAUtil.class.getClassLoader()
.getResource("rsa_private_key.pem").getPath();
String filePath = RSAUtil.class.getClassLoader().getResource("rsa_private_key.pem").getPath();
InputStream in = new FileInputStream(filePath);
BufferedReader br = new BufferedReader(new InputStreamReader(in));
String readLine;
@@ -108,9 +107,7 @@ public class RSAUtil {
br.close();
return loadPrivateKey(sb.toString());
} catch (IOException e) {
throw new Exception("私钥数据读取错误");
} catch (NullPointerException e) {
throw new Exception("私钥输入流为空");
throw new UtilException("私钥数据读取错误");
}
}
@@ -121,8 +118,7 @@ public class RSAUtil {
* @return
* @throws Exception
*/
public static RSAPrivateKey loadPrivateKey(String privateKeyStr)
throws Exception {
public static RSAPrivateKey loadPrivateKey(String privateKeyStr) {
try {
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] priKeyData = base64Decoder.decodeBuffer(privateKeyStr);
@@ -136,13 +132,14 @@ public class RSAUtil {
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
return (RSAPrivateKey) keyFactory.generatePrivate(rsaPrivKeySpec);
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此算法");
LOGGER.error(e.getMessage());
throw new UtilException("无此算法");
} catch (InvalidKeySpecException e) {
throw new Exception("私钥非法");
LOGGER.error(e.getMessage());
throw new UtilException("私钥非法");
} catch (IOException e) {
throw new Exception("私钥数据内容读取错误");
} catch (NullPointerException e) {
throw new Exception("私钥数据为空");
LOGGER.error(e.getMessage());
throw new UtilException("私钥数据内容读取错误");
}
}
@@ -153,10 +150,9 @@ public class RSAUtil {
* @return
* @throws Exception 加密过程中的异常信息
*/
public static String encrypt(RSAPublicKey publicKey, String data)
throws Exception {
public static String encrypt(RSAPublicKey publicKey, String data) {
if (publicKey == null) {
throw new Exception("加密公钥为空, 请设置");
throw new UtilException("加密公钥为空,请设置");
}
byte[] plainTextData = data.getBytes();
Cipher cipher;
@@ -166,17 +162,18 @@ public class RSAUtil {
byte[] output = cipher.doFinal(plainTextData);// 执行加密操作
BASE64Encoder base64Encoder = new BASE64Encoder();
return base64Encoder.encode(output);// Base64编码成字符串
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此加密算法");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
LOGGER.error(e.getMessage());
throw new UtilException("无此加密算法");
} catch (InvalidKeyException e) {
throw new Exception("加密公钥非法,请检查");
LOGGER.error(e.getMessage());
throw new UtilException("加密公钥非法,请检查");
} catch (IllegalBlockSizeException e) {
throw new Exception("明文长度非法");
LOGGER.error(e.getMessage());
throw new UtilException("明文长度非法");
} catch (BadPaddingException e) {
throw new Exception("明文数据已损坏");
LOGGER.error(e.getMessage());
throw new UtilException("明文数据已损坏");
}
}
@@ -185,9 +182,8 @@ public class RSAUtil {
*
* @param data
* @return
* @throws Exception
*/
public static String encrypt(String data) throws Exception {
public static String encrypt(String data) {
return encrypt(loadPublicKey(), data);
}
@@ -198,29 +194,33 @@ public class RSAUtil {
* @return 明文
* @throws Exception 解密过程中的异常信息
*/
public static String decrypt(RSAPrivateKey privateKey, String data) throws Exception {
public static String decrypt(RSAPrivateKey privateKey, String data) {
if (privateKey == null) {
throw new Exception("解密私钥为空, 请设置");
throw new UtilException("解密私钥为空, 请设置");
}
BASE64Decoder base64Decoder = new BASE64Decoder();
byte[] cipherData = base64Decoder.decodeBuffer(data);
Cipher cipher;
try {
byte[] cipherData = base64Decoder.decodeBuffer(data);
cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] output = cipher.doFinal(cipherData);
return new String(output);
} catch (NoSuchAlgorithmException e) {
throw new Exception("无此解密算法");
} catch (NoSuchPaddingException e) {
e.printStackTrace();
return null;
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
LOGGER.error(e.getMessage());
throw new UtilException("无此解密算法");
} catch (InvalidKeyException e) {
throw new Exception("解密私钥非法,请检查");
LOGGER.error(e.getMessage());
throw new UtilException("解密私钥非法,请检查");
} catch (IllegalBlockSizeException e) {
throw new Exception("密文长度非法");
LOGGER.error(e.getMessage());
throw new UtilException("密文长度非法");
} catch (BadPaddingException e) {
throw new Exception("密文数据已损坏");
LOGGER.error(e.getMessage());
throw new UtilException("密文数据已损坏");
} catch (IOException e) {
LOGGER.error(e.getMessage());
throw new UtilException("解密数据读取失败");
}
}
@@ -229,25 +229,24 @@ public class RSAUtil {
*
* @param data
* @return
* @throws Exception
*/
public static String decrypt(String data) throws Exception {
public static String decrypt(String data){
return decrypt(loadPrivateKey(), data);
}
public static void main(String[] args) throws Exception {
public static void main(String[] args) {
String en = testJiami();// 密文
String de = testJiemi(en);// 明文
System.out.println(de);
}
private static String testJiami() throws Exception {
private static String testJiami(){
String plainText = encrypt(loadPublicKey(), "123456");
System.out.println("加密结果:" + plainText);
return plainText;
}
private static String testJiemi(String str) throws Exception {
private static String testJiemi(String str){
String plainText = decrypt(loadPrivateKey(), str);
System.out.println("解密结果:" + plainText);
return plainText;
@@ -1,5 +1,7 @@
package com.xwbing.util;
import com.xwbing.exception.UtilException;
import java.util.Random;
/**
@@ -13,7 +15,7 @@ public class RadomUtil {
public static String buildRandom(int length) {
if (length < 1)
throw new RuntimeException("参数异常!!!");
throw new UtilException("参数异常!!!");
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
@@ -1,5 +1,6 @@
package com.xwbing.util;
import com.xwbing.exception.UtilException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@@ -65,7 +66,7 @@ public class ZipUtil {
zipFile.delete();
} catch (Exception e) {
LOGGER.error(e.getMessage());
throw new RuntimeException("文件压缩错误");
throw new UtilException("文件压缩错误");
}
}
@@ -91,7 +92,7 @@ public class ZipUtil {
bos.close();
} catch (IOException e) {
LOGGER.error(e.getMessage());
throw new RuntimeException("文件转化错误");
throw new UtilException("文件转化错误");
}
return bytes;
}
@@ -4,13 +4,12 @@ import com.alibaba.fastjson.JSONObject;
import com.xwbing.annotation.LogInfo;
import com.xwbing.domain.entity.ExpressInfo;
import com.xwbing.domain.entity.vo.ExpressInfoVo;
import com.xwbing.exception.BusinessException;
import com.xwbing.redis.RedisService;
import com.xwbing.service.ExpressDeliveryService;
import com.xwbing.service.QRCodeZipService;
import com.xwbing.util.HttpClientUtil;
import com.xwbing.util.JSONObjResult;
import com.xwbing.util.RSAUtil;
import com.xwbing.util.HttpClientUtil;
import com.xwbing.util.RestMessage;
import io.swagger.annotations.Api;
import org.apache.commons.lang3.StringUtils;
@@ -101,13 +100,9 @@ public class TestControl {
@LogInfo("rsa")
@GetMapping("rsa")
public void rsa() {
try {
String en = RSAUtil.encrypt("123456");
String de = RSAUtil.decrypt(en);
System.out.println(de);
} catch (Exception ex) {
throw new BusinessException(ex.getMessage());
}
String en = RSAUtil.encrypt("123456");
String de = RSAUtil.decrypt(en);
System.out.println(de);
}
@LogInfo("httpClient")
@@ -115,7 +110,7 @@ public class TestControl {
public JSONObject httpClient(@RequestBody JSONObject param) {
// String url = "http://localhost:8080/user/listAll";
// return HttpClientUtil.get(url);
String url="http://localhost:8080/user/save";
String url = "http://localhost:8080/user/save";
return HttpClientUtil.postByJson(url, param);
}
}
@@ -91,19 +91,6 @@ public class GlobalExceptionHandler {
return JSONObjResult.toJSONObj(stringBuffer.toString());
}
/**
* 处理运行异常
* @param ex
* @return
*/
@ExceptionHandler(value = RuntimeException.class)
@ResponseStatus(value = HttpStatus.INTERNAL_SERVER_ERROR)
@ResponseBody
public JSONObject handlerRuntimeException(RuntimeException ex) {
logger.error(ex.getMessage());
return JSONObjResult.toJSONObj(ex.getMessage());
}
/**
* 全部捕获
* @param ex