下载地址:
BigDecimalUtil | BigDecimalUtil计算工具类 |
---|
CaptchaUtil | 图片验证码工具类 | CoordinateTransformUtil | 坐标系转换工具类 | DateUtil | 日期加减工具类 | EmailUtil | email发送工具类 | EncodeDecodeUtil | 加密工具类 | GzipUtil | 压缩工具类 | HttpClient | http远程调用工具类 | JwtUtil | jwt工具类 | LanguageUtil | 语种工具类 | MD5 | MD5加密工具类 | ObjectDeepCopyUtil | 对象深度拷贝工具类 | OrderNoUtil | 订单号工具类 | PoolPrintUtil | 线程池打印工具类 | RandomUtil | 手机验证码生成工具类 | ResponseEntity | 统一结果返回类 | ResponseUtil | 结果响应工具类 | XmlUtil | xml转换map工具类 |
持续更新中…
1.BigDecimalUtil
public class BigDecimalUtil {
public static double subtract(double x, double y) {
BigDecimal d1 = BigDecimal.valueOf(x);
BigDecimal d2 = BigDecimal.valueOf(y);
return d1.subtract(d2).doubleValue();
}
public static double subtractUp(double x, double y) {
double value = subtract(x, y);
return roundUp(value);
}
public static double subtractDown(double x, double y) {
double value = subtract(x, y);
return roundDown(value);
}
public static double add(double x, double y) {
BigDecimal d1 = BigDecimal.valueOf(x);
BigDecimal d2 = BigDecimal.valueOf(y);
return d1.add(d2).doubleValue();
}
public static double multiply(double x, double y) {
BigDecimal d1 = BigDecimal.valueOf(x);
BigDecimal d2 = BigDecimal.valueOf(y);
return d1.multiply(d2).doubleValue();
}
public static double divide(double x, double y, int scale) {
BigDecimal d1 = BigDecimal.valueOf(x);
BigDecimal d2 = BigDecimal.valueOf(y);
return d1.divide(d2, scale).doubleValue();
}
public static double roundUp(double val) {
return roundUp(val, 0);
}
public static double roundUp(double val, int scale) {
BigDecimal dec = BigDecimal.valueOf(val);
return dec.setScale(scale, RoundingMode.UP).doubleValue();
}
public static double roundDown(double val) {
return roundDown(val, 0);
}
public static double roundDown(double val, int scale) {
BigDecimal dec = BigDecimal.valueOf(val);
return dec.setScale(scale, RoundingMode.DOWN).doubleValue();
}
public static double roundHalfUp(double val) {
return roundHalfUp(val, 0);
}
public static double roundHalfUp(double val, int scale) {
BigDecimal dec = BigDecimal.valueOf(val);
return dec.setScale(scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}
}
2.CaptchaUtil 图片验证码工具类
public class CaptchaUtil {
static char[] chars = {'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J',
'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W',
'X', 'Y', 'Z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'};
public static String genCaptcha(int count) {
StringBuilder captcha = new StringBuilder();
for (int i = 0; i < count; i++) {
char c = chars[ThreadLocalRandom.current().nextInt(chars.length)];
captcha.append(c);
}
return captcha.toString();
}
public static BufferedImage genCaptchaImg(String captcha) {
ThreadLocalRandom r = ThreadLocalRandom.current();
int count = captcha.length();
int fontSize = 80;
int fontMargin = fontSize / 4;
int width = (fontSize + fontMargin) * count + fontMargin;
int height = (int) (fontSize * 1.2);
int avgWidth = width / count;
int maxDegree = 26;
Color bkColor = Color.WHITE;
Color[] catchaColor = {Color.MAGENTA, Color.BLACK, Color.BLUE, Color.CYAN, Color.GREEN, Color.ORANGE, Color.PINK};
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = image.createGraphics();
g.setColor(bkColor);
g.fillRect(0, 0, width, height);
g.setColor(Color.WHITE);
g.drawRect(0, 0, width - 1, height - 1);
int dSize = fontSize / 3;
Font font = new Font("Fixedsys", Font.PLAIN, dSize);
g.setFont(font);
int dNumber = width * height / dSize / dSize;
for (int i = 0; i < dNumber; i++) {
char d_code = chars[r.nextInt(chars.length)];
g.setColor(new Color(r.nextInt(255), r.nextInt(255), r.nextInt(255)));
g.drawString(String.valueOf(d_code), r.nextInt(width), r.nextInt(height));
}
font = new Font(Font.MONOSPACED, Font.ITALIC | Font.BOLD, fontSize);
g.setFont(font);
for (int i = 0; i < count; i++) {
char c = captcha.charAt(i);
g.setColor(catchaColor[r.nextInt(catchaColor.length)]);
int degree = r.nextInt(-maxDegree, maxDegree + 1);
double offsetFactor = 1 - (Math.abs(degree) / (maxDegree + 1.0));
g.rotate(degree * Math.PI / 180);
int x = (int) (fontMargin + r.nextInt(avgWidth - fontSize) * offsetFactor);
int y = (int) (fontSize + r.nextInt(height - fontSize) * offsetFactor);
g.drawString(String.valueOf(c), x, y);
g.rotate(-degree * Math.PI / 180);
g.translate(avgWidth, 0);
}
g.dispose();
return image;
}
}
3.CoordinateTransformUtil 坐标系转换工具类
public class CoordinateTransformUtil {
static double x_pi = 3.14159265358979324 * 3000.0 / 180.0;
static double pi = 3.1415926535897932384626;
static double a = 6378245.0;
static double ee = 0.00669342162296594323;
public static double[] convertLatLonByCoordinate(String newCoordinateType, String originalCoordinateType, double lat, double lon) {
if (originalCoordinateType == null) {
return null;
}
boolean bd09ToWgs84 = (originalCoordinateType.equalsIgnoreCase("bd09") || originalCoordinateType.equalsIgnoreCase("baidu")
&& (newCoordinateType.equalsIgnoreCase("google")) || newCoordinateType.equalsIgnoreCase("wgs84"));
boolean gcj02toWgs84 = (originalCoordinateType.equalsIgnoreCase("gaode") || originalCoordinateType.equalsIgnoreCase("gcj02")
&& (newCoordinateType.equalsIgnoreCase("google")) || newCoordinateType.equalsIgnoreCase("wgs84"));
boolean wgs84ToBd09 = (originalCoordinateType.equalsIgnoreCase("google") || originalCoordinateType.equalsIgnoreCase("wgs84"))
&& (newCoordinateType.equalsIgnoreCase("bd09") || newCoordinateType.equalsIgnoreCase("baidu"));
boolean gcj02ToBd09 = (originalCoordinateType.equalsIgnoreCase("gaode") || originalCoordinateType.equalsIgnoreCase("gcj02"))
&& (newCoordinateType.equalsIgnoreCase("bd09") || newCoordinateType.equalsIgnoreCase("baidu"));
boolean wgs84ToGcj02 = (originalCoordinateType.equalsIgnoreCase("google") || originalCoordinateType.equalsIgnoreCase("wgs84"))
&& (newCoordinateType.equalsIgnoreCase("gaode") || newCoordinateType.equalsIgnoreCase("gcj02"));
boolean bd09ToGcj02 = (originalCoordinateType.equalsIgnoreCase("bd09") || originalCoordinateType.equalsIgnoreCase("baidu"))
&& (newCoordinateType.equalsIgnoreCase("gaode") || newCoordinateType.equalsIgnoreCase("gcj02"));
if (originalCoordinateType.equals(newCoordinateType)) {
return new double[]{lat, lon};
} else if (bd09ToWgs84) {
return bd09towgs84(lon, lat);
} else if (gcj02toWgs84) {
return gcj02towgs84(lon, lat);
} else if (wgs84ToBd09) {
return wgs84tobd09(lon, lat);
} else if (gcj02ToBd09) {
return gcj02tobd09(lon, lat);
} else if (wgs84ToGcj02) {
return wgs84togcj02(lon, lat);
} else if (bd09ToGcj02) {
return bd09togcj02(lon, lat);
} else {
return null;
}
}
public static double[] bd09towgs84(double lng, double lat) {
double[] gcj = bd09togcj02(lng, lat);
double[] wgs84 = gcj02towgs84(gcj[0], gcj[1]);
return wgs84;
}
public static double[] wgs84tobd09(double lng, double lat) {
double[] gcj = wgs84togcj02(lng, lat);
double[] bd09 = gcj02tobd09(gcj[0], gcj[1]);
return bd09;
}
public static double[] gcj02tobd09(double lng, double lat) {
double z = Math.sqrt(lng * lng + lat * lat) + 0.00002 * Math.sin(lat * x_pi);
double theta = Math.atan2(lat, lng) + 0.000003 * Math.cos(lng * x_pi);
double bd_lng = z * Math.cos(theta) + 0.0065;
double bd_lat = z * Math.sin(theta) + 0.006;
return new double[] { bd_lng, bd_lat };
}
public static double[] bd09togcj02(double bd_lon, double bd_lat) {
double x = bd_lon - 0.0065;
double y = bd_lat - 0.006;
double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * x_pi);
double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * x_pi);
double gg_lng = z * Math.cos(theta);
double gg_lat = z * Math.sin(theta);
return new double[] { gg_lng, gg_lat };
}
public static double[] wgs84togcj02(double lng, double lat) {
if (out_of_china(lng, lat)) {
return new double[] { lng, lat };
}
double dlat = transformlat(lng - 105.0, lat - 35.0);
double dlng = transformlng(lng - 105.0, lat - 35.0);
double radlat = lat / 180.0 * pi;
double magic = Math.sin(radlat);
magic = 1 - ee * magic * magic;
double sqrtmagic = Math.sqrt(magic);
dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi);
dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * pi);
double mglat = lat + dlat;
double mglng = lng + dlng;
return new double[] { mglng, mglat };
}
public static double[] gcj02towgs84(double lng, double lat) {
if (out_of_china(lng, lat)) {
return new double[] { lng, lat };
}
double dlat = transformlat(lng - 105.0, lat - 35.0);
double dlng = transformlng(lng - 105.0, lat - 35.0);
double radlat = lat / 180.0 * pi;
double magic = Math.sin(radlat);
magic = 1 - ee * magic * magic;
double sqrtmagic = Math.sqrt(magic);
dlat = (dlat * 180.0) / ((a * (1 - ee)) / (magic * sqrtmagic) * pi);
dlng = (dlng * 180.0) / (a / sqrtmagic * Math.cos(radlat) * pi);
double mglat = lat + dlat;
double mglng = lng + dlng;
return new double[] { lng * 2 - mglng, lat * 2 - mglat };
}
public static double transformlat(double lng, double lat) {
double ret = -100.0 + 2.0 * lng + 3.0 * lat + 0.2 * lat * lat + 0.1 * lng * lat + 0.2 * Math.sqrt(Math.abs(lng));
ret += (20.0 * Math.sin(6.0 * lng * pi) + 20.0 * Math.sin(2.0 * lng * pi)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(lat * pi) + 40.0 * Math.sin(lat / 3.0 * pi)) * 2.0 / 3.0;
ret += (160.0 * Math.sin(lat / 12.0 * pi) + 320 * Math.sin(lat * pi / 30.0)) * 2.0 / 3.0;
return ret;
}
public static double transformlng(double lng, double lat) {
double ret = 300.0 + lng + 2.0 * lat + 0.1 * lng * lng + 0.1 * lng * lat + 0.1 * Math.sqrt(Math.abs(lng));
ret += (20.0 * Math.sin(6.0 * lng * pi) + 20.0 * Math.sin(2.0 * lng * pi)) * 2.0 / 3.0;
ret += (20.0 * Math.sin(lng * pi) + 40.0 * Math.sin(lng / 3.0 * pi)) * 2.0 / 3.0;
ret += (150.0 * Math.sin(lng / 12.0 * pi) + 300.0 * Math.sin(lng / 30.0 * pi)) * 2.0 / 3.0;
return ret;
}
public static boolean out_of_china(double lng, double lat) {
if (lng < 72.004 || lng > 137.8347) {
return true;
} else if (lat < 0.8293 || lat > 55.8271) {
return true;
}
return false;
}
}
4.DateUtil 日期加减工具类
public class DateUtil {
private static final String dateFormat = "yyyy-MM-dd";
public static String formatDate(Date date) {
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
return sdf.format(date);
}
public static Date addDays(Date date, int amount) {
Calendar now =Calendar.getInstance();
now.setTime(date);
now.set(Calendar.DATE,now.get(Calendar.DATE)+amount);
return now.getTime();
}
public static void main(String[] args) {
System.out.println(DateUtil.formatDate(new Date()));
System.out.println(DateUtil.formatDate(DateUtil.addDays(new Date(), -1)));
}
}
5.EmailUtil email发送工具类
public class EmailUtil {
private static Session session;
private static String user;
private MimeMessage msg;
private String text;
private String html;
private List<MimeBodyPart> attachments = new ArrayList<MimeBodyPart>();
private EmailUtil() {
}
public static Properties defaultConfig(Boolean debug) {
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.ssl.enable", "true");
props.put("mail.debug", "false");
props.put("mail.transport.protocol", "smtp");
props.put("mail.debug", null != debug ? debug.toString() : "false");
props.put("mail.smtp.timeout", "10000");
props.put("mail.smtp.port", "465");
return props;
}
public static Properties SMTP_ENT_QQ(boolean debug) {
Properties props = defaultConfig(debug);
props.put("mail.smtp.host", "smtp.exmail.qq.com");
return props;
}
public static Properties SMTP_QQ(boolean debug) {
Properties props = defaultConfig(debug);
props.put("mail.smtp.host", "smtp.qq.com");
return props;
}
public static Properties SMTP_163(Boolean debug) {
Properties props = defaultConfig(debug);
props.put("mail.smtp.host", "smtp.163.com");
return props;
}
public static void config(Properties props, final String username, final String password) {
props.setProperty("username", username);
props.setProperty("password", password);
config(props);
}
public static void config(Properties props) {
final String username = props.getProperty("username");
final String password = props.getProperty("password");
user = username;
session = Session.getInstance(props, new Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
}
public static EmailUtil subject(String subject) throws MessagingException {
EmailUtil emailUtil = new EmailUtil();
emailUtil.msg = new MimeMessage(session);
emailUtil.msg.setSubject(subject, "UTF-8");
return emailUtil;
}
public EmailUtil from(String nickName) throws MessagingException {
return from(nickName, user);
}
public EmailUtil from(String nickName, String from) throws MessagingException {
try {
nickName = MimeUtility.encodeText(nickName);
} catch (Exception e) {
e.printStackTrace();
}
msg.setFrom(new InternetAddress(nickName + " <" + from + ">"));
return this;
}
public EmailUtil replyTo(String... replyTo) throws MessagingException {
String result = Arrays.asList(replyTo).toString().replaceAll("(^\\[|\\]$)", "").replace(", ", ",");
msg.setReplyTo(InternetAddress.parse(result));
return this;
}
public EmailUtil replyTo(String replyTo) throws MessagingException {
msg.setReplyTo(InternetAddress.parse(replyTo.replace(";", ",")));
return this;
}
public EmailUtil to(String... to) throws Exception {
return addRecipients(to, Message.RecipientType.TO);
}
public EmailUtil to(String to) throws MessagingException {
return addRecipient(to, Message.RecipientType.TO);
}
public EmailUtil cc(String... cc) throws MessagingException {
return addRecipients(cc, Message.RecipientType.CC);
}
public EmailUtil cc(String cc) throws MessagingException {
return addRecipient(cc, Message.RecipientType.CC);
}
public EmailUtil bcc(String... bcc) throws MessagingException {
return addRecipients(bcc, Message.RecipientType.BCC);
}
public EmailUtil bcc(String bcc) throws MessagingException {
return addRecipient(bcc, Message.RecipientType.BCC);
}
private EmailUtil addRecipients(String[] recipients, Message.RecipientType type) throws MessagingException {
String result = Arrays.asList(recipients).toString().replace("(^\\[|\\]$)", "").replace(", ", ",");
msg.setRecipients(type, InternetAddress.parse(result));
return this;
}
private EmailUtil addRecipient(String recipient, Message.RecipientType type) throws MessagingException {
msg.setRecipients(type, InternetAddress.parse(recipient.replace(";", ",")));
return this;
}
public EmailUtil text(String text) {
this.text = text;
return this;
}
public EmailUtil html(String html) {
this.html = html;
return this;
}
public EmailUtil attach(File file) throws MessagingException {
attachments.add(createAttachment(file, null));
return this;
}
public EmailUtil attach(File file, String fileName) throws MessagingException {
attachments.add(createAttachment(file, fileName));
return this;
}
private MimeBodyPart createAttachment(File file, String fileName) throws MessagingException {
MimeBodyPart attachmentPart = new MimeBodyPart();
FileDataSource fds = new FileDataSource(file);
attachmentPart.setDataHandler(new DataHandler(fds));
try {
attachmentPart.setFileName(null == fileName ? MimeUtility.encodeText(fds.getName()) : MimeUtility.encodeText(fileName));
} catch (Exception e) {
e.printStackTrace();
}
return attachmentPart;
}
public void send() throws MessagingException {
if (text == null && html == null)
throw new NullPointerException("At least one context has to be provided: Text or Html");
MimeMultipart cover;
boolean usingAlternative = false;
boolean hasAttachments = attachments.size() > 0;
if (text != null && html == null) {
cover = new MimeMultipart("mixed");
cover.addBodyPart(textPart());
} else if (text == null && html != null) {
cover = new MimeMultipart("mixed");
cover.addBodyPart(htmlPart());
} else {
cover = new MimeMultipart("alternative");
cover.addBodyPart(textPart());
cover.addBodyPart(htmlPart());
usingAlternative = true;
}
MimeMultipart content = cover;
if (usingAlternative && hasAttachments) {
content = new MimeMultipart("mixed");
content.addBodyPart(toBodyPart(cover));
}
for (MimeBodyPart attachment : attachments) {
content.addBodyPart(attachment);
}
msg.setContent(content);
msg.setSentDate(new Date());
Transport.send(msg);
}
private MimeBodyPart toBodyPart(MimeMultipart cover) throws MessagingException {
MimeBodyPart wrap = new MimeBodyPart();
wrap.setContent(cover);
return wrap;
}
private MimeBodyPart textPart() throws MessagingException {
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setText(text);
return bodyPart;
}
private MimeBodyPart htmlPart() throws MessagingException {
MimeBodyPart bodyPart = new MimeBodyPart();
bodyPart.setContent(html, "text/html; charset=utf-8");
return bodyPart;
}
}
6.EncodeDecodeUtil 加密工具类
public class EncodeDecodeUtil {
private static final char[] HEX = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
private static final String DEFAULT_CHARSET = "utf-8";
public static String encodeWithMD5(String str) {
return encode("MD5", str);
}
public static String encodeWithSHA1(String str) {
return encode("SHA1", str);
}
public static String encodeWithSHA256(String str) {
return encode("SHA-256", str);
}
public static String encode(String algorithm, String str) {
if (str == null) {
return null;
}
try {
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
messageDigest.update(str.getBytes());
return getFormattedText(messageDigest.digest());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String encodeBase64(String str) {
if (StringUtils.isBlank(str)) {
return null;
}
try {
return Base64.getEncoder().encodeToString(str.getBytes(DEFAULT_CHARSET));
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String decodeBase64(String str) {
if (StringUtils.isBlank(str)) {
return null;
}
try {
byte[] bytes = Base64.getDecoder().decode(str);
return new String(bytes, DEFAULT_CHARSET);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String decodeUrl(String str) {
if (StringUtils.isBlank(str)) {
return null;
}
try {
return java.net.URLDecoder.decode(str, "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static String encodeUrl(String str) {
if (StringUtils.isBlank(str)) {
return null;
}
try {
return java.net.URLEncoder.encode(str, "UTF-8");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
private static String getFormattedText(byte[] bytes) {
int len = bytes.length;
StringBuilder buf = new StringBuilder(len * 2);
for (int j = 0; j < len; j++) {
buf.append(HEX[(bytes[j] >> 4) & 0x0f]);
buf.append(HEX[bytes[j] & 0x0f]);
}
return buf.toString();
}
}
7.GzipUtil 压缩工具类
public class GzipUtil {
private static Logger logger = LoggerFactory.getLogger(GZIPUtil.class);
public static final String GZIP_ENCODE_UTF_8 = "UTF-8";
public static byte[] compress(String str) {
return compress(str, GZIP_ENCODE_UTF_8);
}
public static byte[] compress(String str, String encoding) {
if (str == null || str.length() == 0) {
return null;
}
byte[] bytes = null;
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
GZIPOutputStream gzip;
try {
gzip = new GZIPOutputStream(out);
gzip.write(str.getBytes(encoding));
gzip.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
bytes = out.toByteArray();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return bytes;
}
public static byte[] compress(byte[] bytes) {
if (bytes == null || bytes.length == 0) {
return null;
}
byte[] byteArr = null;
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
GZIPOutputStream gzip = null;
try {
gzip = new GZIPOutputStream(out);
gzip.write(bytes);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}finally {
if(gzip!=null){
gzip.close();
}
}
byteArr = out.toByteArray();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return byteArr;
}
public static byte[] uncompress(byte[] bytes) {
if (bytes == null || bytes.length == 0) {
return null;
}
byte[] byteArr = null;
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
GZIPInputStream ungzip = new GZIPInputStream(in);
try {
byte[] buffer = new byte[256];
int n;
while ((n = ungzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
in.close();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}finally {
ungzip.close();
}
byteArr = out.toByteArray();
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return byteArr;
}
public static String uncompress2Str(byte[] bytes) {
return uncompress2Str(bytes, GZIP_ENCODE_UTF_8);
}
public static String uncompress2Str(byte[] bytes, String encoding) {
if (bytes == null || bytes.length == 0) {
return null;
}
String str = null;
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
ByteArrayInputStream in = new ByteArrayInputStream(bytes);
try {
GZIPInputStream ungzip = new GZIPInputStream(in);
byte[] buffer = new byte[256];
int n;
while ((n = ungzip.read(buffer)) >= 0) {
out.write(buffer, 0, n);
}
in.close();
ungzip.close();
str = out.toString(encoding);
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
} catch (IOException e) {
logger.error(e.getMessage(), e);
}
return str;
}
}
8.HttpClient http远程调用工具类
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.*;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import javax.net.ssl.SSLContext;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.ParseException;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public class HttpClient {
private String url;
private Map<String, String> param;
private int statusCode;
private String content;
private String xmlParam;
private boolean isHttps;
public boolean isHttps() {
return isHttps;
}
public void setHttps(boolean isHttps) {
this.isHttps = isHttps;
}
public String getXmlParam() {
return xmlParam;
}
public void setXmlParam(String xmlParam) {
this.xmlParam = xmlParam;
}
public HttpClient(String url, Map<String, String> param) {
this.url = url;
this.param = param;
}
public HttpClient(String url) {
this.url = url;
}
public void setParameter(Map<String, String> map) {
param = map;
}
public void addParameter(String key, String value) {
if (param == null)
param = new HashMap<String, String>();
param.put(key, value);
}
public void post() throws ClientProtocolException, IOException {
HttpPost http = new HttpPost(url);
setEntity(http);
execute(http);
}
public void put() throws ClientProtocolException, IOException {
HttpPut http = new HttpPut(url);
setEntity(http);
execute(http);
}
public void get() throws ClientProtocolException, IOException {
if (param != null) {
StringBuilder url = new StringBuilder(this.url);
boolean isFirst = true;
for (String key : param.keySet()) {
if (isFirst)
url.append("?");
else
url.append("&");
url.append(key).append("=").append(param.get(key));
}
this.url = url.toString();
}
HttpGet http = new HttpGet(url);
execute(http);
}
private void setEntity(HttpEntityEnclosingRequestBase http) {
if (param != null) {
List<NameValuePair> nvps = new LinkedList<NameValuePair>();
for (String key : param.keySet())
nvps.add(new BasicNameValuePair(key, param.get(key)));
http.setEntity(new UrlEncodedFormEntity(nvps, Consts.UTF_8));
}
if (xmlParam != null) {
http.setEntity(new StringEntity(xmlParam, Consts.UTF_8));
}
}
private void execute(HttpUriRequest http) throws ClientProtocolException,
IOException {
CloseableHttpClient httpClient = null;
try {
if (isHttps) {
SSLContext sslContext = new SSLContextBuilder()
.loadTrustMaterial(null, new TrustStrategy() {
public boolean isTrusted(X509Certificate[] chain,
String authType)
throws CertificateException {
return true;
}
}).build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslContext);
httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
.build();
} else {
httpClient = HttpClients.createDefault();
}
CloseableHttpResponse response = httpClient.execute(http);
try {
if (response != null) {
if (response.getStatusLine() != null)
statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
content = EntityUtils.toString(entity, Consts.UTF_8);
}
} finally {
response.close();
}
} catch (Exception e) {
e.printStackTrace();
} finally {
httpClient.close();
}
}
public int getStatusCode() {
return statusCode;
}
public String getContent() throws ParseException, IOException {
return content;
}
}
9.JwtUtil jwt工具类
public class JwtUtils {
public static final long EXPIRATION = 1000 * 60 * 60 * 24;
public static final String SECRET = "ukc8BDbRigUDaY6pZFfWus2jZWLPHO";
public static String getToken(String id, String nickname) {
return Jwts.builder()
.setHeaderParam("typ", "JWT")
.setHeaderParam("alg", "HS256")
.setSubject("online-encourage")
.setIssuedAt(new Date())
.setExpiration(new Date(System.currentTimeMillis() + EXPIRATION))
.claim("id", id)
.claim("nickname", nickname)
.signWith(SignatureAlgorithm.HS256, SECRET)
.compact();
}
public static boolean isExpiration(String token) {
if (StringUtils.isEmpty(token)) {
return false;
}
Date expiration = getClaimByToken(token).getExpiration();
return expiration.before(new Date());
}
public static Claims getClaimByToken(String token) {
return Jwts.parser().setSigningKey(SECRET).parseClaimsJws(token).getBody();
}
public static String getUserIdByToken(HttpServletRequest request) {
String token = request.getHeader("token");
System.out.println("token为:--->>>>>>>>>>>>>>"+token);
if (StringUtils.isEmpty(token)) {
return "";
}
return (String) getClaimByToken(token).get("id");
}
}
10.LanguageUtil 语种工具类
public class LanguageUtil {
public static boolean isNumeric(String str) {
return str != null && str.length() > 0 && Pattern.matches("[0-9]*", str);
}
public static boolean isOnlyLetter(String str) {
return str != null && str.length() > 0 && Pattern.matches("^[A-Za-z]+$", str);
}
public static boolean isLetter(String str) {
return str != null && str.length() > 0 && Pattern.matches("^[A-Za-z\\u0020]+$", str);
}
public static boolean isChinese(String str) {
return str != null && str.length() > 0 && Pattern.matches("^[\\u4e00-\\u9fa5\\u0020]+$", str);
}
public static boolean isLetterAndNumber(String str) {
return str != null && str.length() > 0 && Pattern.matches("^[0-9A-Za-z\\u0020]+$", str);
}
public static boolean isChineseAndNumber(String str) {
return str != null && str.length() > 0 && Pattern.matches("^[0-9\\u4e00-\\u9fa5\\u0020]+$", str);
}
public static boolean isKoreanAndNumber(String str) {
return str != null && str.length() > 0 && Pattern.matches("^[0-9\\uac00-\\ud7a3\\u0020]+$", str);
}
public static boolean isJapanAndNumber(String str) {
return str != null && str.length() > 0 && Pattern.matches("^[0-9\\u0800-\\u4e00\\u0020]+$", str);
}
}
11.MD5 MD5加密工具类
public final class MD5 {
public static String encrypt(String strSrc) {
try {
char hexChars[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
'9', 'a', 'b', 'c', 'd', 'e', 'f' };
byte[] bytes = strSrc.getBytes();
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(bytes);
bytes = md.digest();
int j = bytes.length;
char[] chars = new char[j * 2];
int k = 0;
for (int i = 0; i < bytes.length; i++) {
byte b = bytes[i];
chars[k++] = hexChars[b >>> 4 & 0xf];
chars[k++] = hexChars[b & 0xf];
}
return new String(chars);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
throw new RuntimeException("MD5加密出错!!+" + e);
}
}
}
12.ObjectDeepCopyUtil 对象深度拷贝工具类
public class ObjectDeepCopyUtil {
public static Object depthClone(Object srcObj) {
Object cloneObj = null;
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oo = new ObjectOutputStream(out);
oo.writeObject(srcObj);
ByteArrayInputStream in = new ByteArrayInputStream(
out.toByteArray());
ObjectInputStream oi = new ObjectInputStream(in);
cloneObj = oi.readObject();
} catch (Exception ex) {
return null;
}
return cloneObj;
}
public static <T> List<T> listDepthClone(List<T> list) {
List<T> newList = new ArrayList<>();
for (Object item : list) {
if (item == null) {
continue;
}
Object val = depthClone(item);
if (val != null) {
newList.add((T) val);
}
}
return newList;
}
}
13.OrderNoUtil 订单号工具类
public class OrderNoUtil {
public static String getOrderNo() {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
String newDate = sdf.format(new Date());
String result = "";
Random random = new Random();
for (int i = 0; i < 3; i++) {
result += random.nextInt(10);
}
return newDate + result;
}
}
14.PoolPrintUtil 线程池打印工具类
public class PoolPrintUtil {
public void printThreadPoolStatus(ThreadPoolExecutor executor, Logger logger) {
int poolSize = executor.getPoolSize();
int corePoolSize = executor.getCorePoolSize();
int activeCount = executor.getActiveCount();
long completedTaskCount = executor.getCompletedTaskCount();
long taskCount = executor.getTaskCount();
int queueCount = executor.getQueue().size();
int largestPoolSize = executor.getLargestPoolSize();
int maximumPoolSize = executor.getMaximumPoolSize();
long time = executor.getKeepAliveTime(TimeUnit.MILLISECONDS);
boolean isShutDown = executor.isShutdown();
boolean isTerminated = executor.isTerminated();
String info = String.format("初始线程数:%s、核心线程数:%s、正在执行的任务数量:%s、已完成任务数量:%s、任务总数:%s、" +
"队列里缓存的任务数量:%s、池中存在的最大线程数:%s、最大允许的线程数:%s、线程空闲时间:%s、线程池是否关闭:%s、" +
"线程池是否终止:%s", poolSize, corePoolSize, activeCount, completedTaskCount, taskCount, queueCount,
largestPoolSize, maximumPoolSize, time, isShutDown, isTerminated);
logger.info(info);
}
public void printThreadPoolStatus(Logger logger, ThreadPoolExecutor... executors) {
for (int i=0; i< executors.length; i++) {
printThreadPoolStatus(executors[i], logger);
}
}
}
15.RandomUtil 手机验证码生成工具类
public class RandomUtil {
private static final Random random = new Random();
private static final DecimalFormat fourdf = new DecimalFormat("0000");
private static final DecimalFormat sixdf = new DecimalFormat("000000");
public static String getFourBitRandom() {
return fourdf.format(random.nextInt(10000));
}
public static String getSixBitRandom() {
return sixdf.format(random.nextInt(1000000));
}
public static ArrayList getRandom(List list, int n) {
Random random = new Random();
HashMap<Object, Object> hashMap = new HashMap<Object, Object>();
for (int i = 0; i < list.size(); i++) {
int number = random.nextInt(100) + 1;
hashMap.put(number, i);
}
Object[] robjs = hashMap.values().toArray();
ArrayList r = new ArrayList();
for (int i = 0; i < n; i++) {
r.add(list.get((int) robjs[i]));
System.out.print(list.get((int) robjs[i]) + "\t");
}
System.out.print("\n");
return r;
}
}
16.ResponseEntity 统一结果返回类
@Data
@Accessors(chain = true)
@ApiModel(value = "统一结果返回类")
public class ResponseEntity {
@ApiModelProperty(value = "是否成功")
private Boolean success;
@ApiModelProperty(value = "状态码")
private Integer code;
@ApiModelProperty(value = "返回消息")
private String msg;
@ApiModelProperty(value = "返回数据")
private Map<String, Object> data = new HashMap<>();
private ResponseEntity() {}
public static ResponseEntity ok() {
return new ResponseEntity()
.setSuccess(true)
.setCode(ResultCode.SUCCESS_CODE)
.setMsg("成功");
}
public static ResponseEntity error() {
return new ResponseEntity()
.setSuccess(false)
.setCode(ResultCode.FAIL_CODE)
.setMsg("失败");
}
public ResponseEntity success(Boolean success) {
this.setSuccess(success);
return this;
}
public ResponseEntity code(Integer code) {
this.setCode(code);
return this;
}
public ResponseEntity msg(String msg) {
this.setMsg(msg);
return this;
}
public ResponseEntity data(String key, Object val) {
this.data.put(key, val);
return this;
}
}
17.ResponseUtil 结果响应工具类
public class ResponseUtil {
public static void out(HttpServletResponse response, ResponseEntity r) {
ObjectMapper mapper = new ObjectMapper();
response.setStatus(HttpStatus.OK.value());
response.setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
try {
mapper.writeValue(response.getWriter(), r);
} catch (IOException e) {
e.printStackTrace();
}
}
}
18.XmlUtil xml转换map工具类
public class XmlUtils {
@SuppressWarnings("unchecked")
public static Map<String, Object> xmlToMap(String xmlDoc) throws JDOMException, IOException {
StringReader read = new StringReader(xmlDoc);
InputSource source = new InputSource(read);
SAXBuilder sb = new SAXBuilder();
Map<String, Object> xmlMap = new HashMap<String, Object>();
Document doc = sb.build(source);
Element root = doc.getRootElement();
List<Element> cNodes = root.getChildren();
Element et = null;
for (int i = 0; i < cNodes.size(); i++) {
et = (Element) cNodes.get(i);
xmlMap.put(et.getName(), et.getText());
}
return xmlMap;
}
@SuppressWarnings("unchecked")
public static Map<String, Object> secondLevelXmlToMap(String xmlDoc) throws JDOMException, IOException {
StringReader read = new StringReader(xmlDoc);
InputSource source = new InputSource(read);
SAXBuilder sb = new SAXBuilder();
Map<String, Object> xmlMap = new HashMap<String, Object>();
Document doc = sb.build(source);
Element root = doc.getRootElement();
List<Element> cNodes = root.getChildren();
Element et = null;
for (int i = 0; i < cNodes.size(); i++) {
et = (Element) cNodes.get(i);
List<Element> etChildrens = et.getChildren();
for (int j = 0 ; j < etChildrens.size() ; j++){
Element ChildrenEt = (Element) etChildrens.get(j);
xmlMap.put(ChildrenEt.getName(), ChildrenEt.getText());
}
}
return xmlMap;
}
}
|