文章目录
- 1.新建模块
- 1.新建模块sun-common-tool
- 2.sun-dependencies指定依赖
- 3.sun-common统一管理sun-common-tool子模块
- 4.sun-common-tool的pom.xml
- 5.清除掉创建模块时默认sun-frame对sun-common-tool进行管理
- 2.常用工具类
- 1.DateUtils.java
- 2.EncodeUtils.java
- 3.IpUtils.java
- 4.LetterUtils.java
- 5.MaskUtils.java
- 6.Md5Utils.java
- 7.PinYin4jUtils.java
- 8.PropertiesUtils.java
- 9.SimpleDateFormatUtils.java
- 10.SpringContextUtils.java
- 11.ThreadPoolUtils.java
- 12.UuidUtils.java
1.新建模块
1.新建模块sun-common-tool
2.sun-dependencies指定依赖
<freemarker.version>2.3.30</freemarker.version><pinyin4j.version>2.5.0</pinyin4j.version><commons.lang3.version>3.8</commons.lang3.version><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId><version>${freemarker.version}</version></dependency><dependency><groupId>com.belerweb</groupId><artifactId>pinyin4j</artifactId><version>${pinyin4j.version}</version></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>${commons.lang3.version}</version></dependency>
3.sun-common统一管理sun-common-tool子模块
4.sun-common-tool的pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>com.sunxiansheng</groupId><artifactId>sun-common</artifactId><version>1.0-SNAPSHOT</version></parent><artifactId>sun-common-tool</artifactId><version>${children.version}</version><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.freemarker</groupId><artifactId>freemarker</artifactId></dependency><dependency><groupId>com.belerweb</groupId><artifactId>pinyin4j</artifactId></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId></dependency></dependencies></project>
5.清除掉创建模块时默认sun-frame对sun-common-tool进行管理
2.常用工具类
1.DateUtils.java
package com.sunxiansheng.tool;import lombok.extern.slf4j.Slf4j;import java.text.SimpleDateFormat;
import java.util.*;
@Slf4j
public class DateUtils {public static final String DATE_FORMAT = "yyyy-MM-dd";public static final String DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";public static final String DATE_MINUTE_FORMAT = "yyyy-MM-dd HH:mm";public static final String MINUTE_FORMAT = "HH:mm";public DateUtils() {}public static Date getStartDate(Calendar calendar) {calendar.set(Calendar.HOUR_OF_DAY, 0);calendar.set(Calendar.MINUTE, 0);calendar.set(Calendar.SECOND, 0);calendar.set(Calendar.MILLISECOND, 0);return calendar.getTime();}public static Date getEndDate(Calendar calendar) {calendar.set(Calendar.HOUR_OF_DAY, 23);calendar.set(Calendar.MINUTE, 59);calendar.set(Calendar.SECOND, 59);calendar.set(Calendar.MILLISECOND, 999);return calendar.getTime();}public static Date addDate(Date date, int day) {long millis = date.getTime() + day * 24L * 3600L * 1000L;Calendar calendar = Calendar.getInstance();calendar.setTimeInMillis(millis);return calendar.getTime();}public static Date getStartDate(Date date) {Calendar calendar = Calendar.getInstance();calendar.setTime(date);calendar.set(Calendar.HOUR_OF_DAY, 0);calendar.set(Calendar.MINUTE, 0);calendar.set(Calendar.SECOND, 0);calendar.set(Calendar.MILLISECOND, 0);return calendar.getTime();}public static Date getEndDate(Date date) {Calendar calendar = Calendar.getInstance();calendar.setTime(date);calendar.set(Calendar.HOUR_OF_DAY, 23);calendar.set(Calendar.MINUTE, 59);calendar.set(Calendar.SECOND, 59);calendar.set(Calendar.MILLISECOND, 999);return calendar.getTime();}public static int weeksOfTwoDates(Date startDate, Date endDate) {Calendar calendar = Calendar.getInstance();calendar.setTime(endDate);int i = 0;while (!endDate.before(startDate)) {i++;calendar.setFirstDayOfWeek(Calendar.MONDAY);calendar.add(Calendar.WEEK_OF_YEAR, -1);calendar.set(Calendar.DAY_OF_WEEK, calendar.getFirstDayOfWeek());calendar.add(Calendar.DAY_OF_MONTH, 6);endDate = calendar.getTime();}return i;}public static Date getCurrentMonday() {int mondayPlus = getMondayPlus();GregorianCalendar currentDate = new GregorianCalendar();currentDate.add(Calendar.DAY_OF_MONTH, mondayPlus);return currentDate.getTime();}public static Date getPreviousSunday() {int mondayPlus = getMondayPlus();GregorianCalendar currentDate = new GregorianCalendar();currentDate.add(Calendar.DAY_OF_MONTH, mondayPlus + 6);return currentDate.getTime();}public static int getMondayPlus() {Calendar cd = Calendar.getInstance();int dayOfWeek = cd.get(Calendar.DAY_OF_WEEK);return dayOfWeek == 1 ? -6 : 2 - dayOfWeek;}public static Calendar getMinMonthDate() {Calendar calendar = Calendar.getInstance();calendar.set(5, calendar.getActualMinimum(5));return calendar;}public static Calendar getMaxMonthDate() {Calendar calendar = Calendar.getInstance();calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));return calendar;}public static Calendar getLastMonday() {Calendar calendar = Calendar.getInstance();int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;int offset = 1 - dayOfWeek;calendar.add(Calendar.DAY_OF_MONTH, offset - 7);return calendar;}public static Calendar getLastSunday() {Calendar calendar = Calendar.getInstance();int dayOfWeek = calendar.get(Calendar.DAY_OF_WEEK) - 1;int offset = Calendar.DAY_OF_WEEK - dayOfWeek;calendar.add(Calendar.DAY_OF_MONTH, offset - 7);return calendar;}public static Calendar getLastMonthFirstDay() {Calendar calendar = Calendar.getInstance();calendar.add(Calendar.MONTH, -1);calendar.set(Calendar.DAY_OF_MONTH, 1);return calendar;}public static Calendar getLastMonthEndDay() {Calendar calendar = Calendar.getInstance();calendar.set(Calendar.DAY_OF_MONTH, 0);return calendar;}public static String getDateStr(Date date) {SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);return date != null ? sdf.format(date) : "";}public static Date getPreDateStr(Date date, int num) {Calendar calendar = Calendar.getInstance();calendar.setTime(date);calendar.add(Calendar.DAY_OF_MONTH, -num);Date time = calendar.getTime();return time;}public static Date getMondayStrOfWeek() {Calendar calendar = Calendar.getInstance();int dayWeek = calendar.get(Calendar.DAY_OF_WEEK);if (dayWeek == 1) {calendar.add(Calendar.DAY_OF_MONTH, -6);} else {calendar.add(Calendar.DAY_OF_MONTH, -(dayWeek - 2));}Date time = calendar.getTime();return time;}public static boolean isLastDayOfMonth(Date date) {Calendar calendar = Calendar.getInstance();calendar.setTime(date);int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);int now = calendar.get(Calendar.DAY_OF_MONTH);return now == lastDay;}public static int daysOfTwo(String startDateStr, String endDateStr) throws Exception {SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);Date startDate = sdf.parse(startDateStr);Date endDate = sdf.parse(endDateStr);return (int) ((endDate.getTime() - startDate.getTime()) / 1000L / 60L / 60L / 24L);}public static List<String> getContinue12Days() {List<String> list = new ArrayList<>();Calendar calendar = Calendar.getInstance();calendar.add(Calendar.DAY_OF_MONTH, -11);SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);for (int i = 0; i <= 11; ++i) {Date time = calendar.getTime();list.add(sdf.format(time));calendar.add(Calendar.DAY_OF_MONTH, 1);}return list;}public static String getWeeksOfYear(String dateStr) throws Exception {SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);Date date = sdf.parse(dateStr);Calendar calendar = Calendar.getInstance();calendar.setTime(date);int i = calendar.get(Calendar.WEEK_OF_YEAR);if (i >= 10) {return dateStr.substring(2, 4) + "-" + i;} else {return dateStr.substring(2, 4) + "-0" + i;}}public static Date getDateByStr(String dateStr) throws Exception {SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);return sdf.parse(dateStr);}public static int daysOfTwoDates(Date startDate, Date endDate) {return (int) ((endDate.getTime() - startDate.getTime()) / 1000L / 60L / 60L / 24L);}public static Date getFirstDayOfMonth(Date date) {Calendar calendar = Calendar.getInstance();calendar.setTime(date);calendar.set(Calendar.DATE, 1);calendar.set(Calendar.HOUR_OF_DAY, 0);calendar.set(Calendar.MINUTE, 0);calendar.set(Calendar.SECOND, 0);return calendar.getTime();}public static final Date getLastDayOfMonth(int year, int month) {Calendar calendar = Calendar.getInstance();calendar.set(Calendar.YEAR, year);calendar.set(Calendar.MONTH, month - 1);int lastDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);calendar.set(Calendar.DAY_OF_MONTH, lastDay);return calendar.getTime();}public static boolean isNow(Date date) {Date now = new Date();SimpleDateFormat sf = new SimpleDateFormat(DATE_FORMAT);String nowDay = sf.format(now);String day = sf.format(date);return day.equals(nowDay);}public static String format(Date date, String format) {SimpleDateFormat sdf = new SimpleDateFormat(format);return sdf.format(date);}public static Date parse(String str, String format) throws Exception {SimpleDateFormat sdf = new SimpleDateFormat(format);return sdf.parse(str);}public static boolean isEffectiveDate(Date nowTime, Date startTime, Date endTime) {if (nowTime.getTime() == startTime.getTime() || nowTime.getTime() == endTime.getTime()) {return true;}Calendar date = Calendar.getInstance();date.setTime(nowTime);Calendar begin = Calendar.getInstance();begin.setTime(startTime);Calendar end = Calendar.getInstance();end.setTime(endTime);return date.after(begin) && date.before(end);}public static String formatLongToDateStr(Long dateTime, String format) {SimpleDateFormat sdf = new SimpleDateFormat(format);return sdf.format(new Date(dateTime));}
}
2.EncodeUtils.java
package com.sunxiansheng.tool;import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Base64;
public class EncodeUtils {private static final String DEFAULT_URL_ENCODING = "UTF-8";private static final Base64.Encoder BASE64_ENCODER = Base64.getEncoder();private static final Base64.Decoder BASE64_DECODER = Base64.getDecoder();public static String encode(String text) throws UnsupportedEncodingException {return BASE64_ENCODER.encodeToString(text.getBytes(DEFAULT_URL_ENCODING));}public static String decode(String encodedText) throws UnsupportedEncodingException {return new String(BASE64_DECODER.decode(encodedText), DEFAULT_URL_ENCODING);}public static String urlEncode(String part) throws UnsupportedEncodingException {return URLEncoder.encode(part, DEFAULT_URL_ENCODING);}public static String urlDecode(String part) throws UnsupportedEncodingException {return URLDecoder.decode(part, DEFAULT_URL_ENCODING);}}
3.IpUtils.java
package com.sunxiansheng.tool;import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
@Slf4j
public class IpUtils {private static final String DEFAULT_IP = "127.0.0.1";private static final String UN_KNOWN = "unknown";private static final int IP_MAX_LENGTH = 15;private static final String SPLIT = ",";private static String getLocalIp() {try {InetAddress localHost = InetAddress.getLocalHost();String localIp = localHost.getHostAddress();log.info("IpUtils.getLocalIp:{}", localIp);return localIp;} catch (Exception e) {log.error("IpUtils.getLocalIp.error:{}", e.getMessage(), e);return DEFAULT_IP;}}public static String getIp(HttpServletRequest request) {String ip = null;try {ip = request.getHeader("x-forwarded-for");if (StringUtils.isEmpty(ip) || UN_KNOWN.equalsIgnoreCase(ip)) {ip = request.getHeader("Proxy-Client-IP");}if (StringUtils.isEmpty(ip) || ip.length() == 0 || UN_KNOWN.equalsIgnoreCase(ip)) {ip = request.getHeader("WL-Proxy-Client-IP");}if (StringUtils.isEmpty(ip) || UN_KNOWN.equalsIgnoreCase(ip)) {ip = request.getHeader("HTTP_CLIENT_IP");}if (StringUtils.isEmpty(ip) || UN_KNOWN.equalsIgnoreCase(ip)) {ip = request.getHeader("HTTP_X_FORWARDED_FOR");}if (StringUtils.isEmpty(ip) || UN_KNOWN.equalsIgnoreCase(ip)) {ip = request.getRemoteAddr();}} catch (Exception e) {log.error("IpUtils.getIp.error:{}", e.getMessage(), e);}if (!StringUtils.isEmpty(ip) && ip.length() > IP_MAX_LENGTH) {if (ip.indexOf(SPLIT) > 0) {ip = ip.substring(0, ip.indexOf(SPLIT));}}return ip;}
}
4.LetterUtils.java
package com.sunxiansheng.tool;import org.apache.commons.lang3.StringUtils;import java.util.Arrays;
import java.util.List;
public class LetterUtils {public static long letterToNumber(String letter) {int length = letter.length();long number = 0;for (int i = 0; i < length; i++) {char ch = letter.charAt(length - i - 1);int num = ch - 'A' + 1;number += num;}return number;}public static String assembleHandler(char splitChar, String... args) {List<String> strList = Arrays.asList(args);return StringUtils.join(strList, splitChar);}}
5.MaskUtils.java
package com.sunxiansheng.tool;import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Slf4j
public class MaskUtils {public static String maskMobile(String mobile) {if (StringUtils.isBlank(mobile)) {return null;}int length = mobile.length();char[] mobileChars = mobile.toCharArray();char[] resultChars = new char[mobile.length()];for (int i = 0; i < length; i++) {if (i >= 3 && i < length - 3) {resultChars[i] = '*';} else {resultChars[i] = mobileChars[i];}}return new String(resultChars);}public static String maskEmail(String email) {if (StringUtils.isBlank(email)) {return null;}int length = email.length();char[] emailChars = email.toCharArray();char[] resultChars = new char[email.length()];int atIndex = email.indexOf('@');for (int i = 0; i < length; i++) {if (i > 0 && i < atIndex - 1) {resultChars[i] = '*';} else {resultChars[i] = emailChars[i];}}return new String(resultChars);}public static String getContext(String html) {String result = html;if (StringUtils.isBlank(html)) {return null;}Pattern p = Pattern.compile(">([^</]+)</");Matcher m = p.matcher(html);if (m.find()) {result = m.group(1);}return result;}public static String maskNickName(String nickName) {if (StringUtils.isBlank(nickName)) {return "";}int length = nickName.length();char[] nickNameChars = nickName.toCharArray();char[] resultChars = new char[nickName.length()];for (int i = 0; i < length; i++) {if (i > 0 && i < length - 1) {resultChars[i] = '*';} else if (i == 1 && length == 2) {resultChars[i] = '*';} else {resultChars[i] = nickNameChars[i];}}return new String(resultChars);}
}
6.Md5Utils.java
package com.sunxiansheng.tool;import java.security.MessageDigest;
public class Md5Utils {public static String encode(String text) {try {MessageDigest md = MessageDigest.getInstance("MD5");md.update(text.getBytes());byte[] digest = md.digest();StringBuilder result = new StringBuilder();for (byte b : digest) {result.append(String.format("%02x", b & 0xff));}return result.toString();} catch (Exception e) {e.printStackTrace();return null;}}}
7.PinYin4jUtils.java
package com.sunxiansheng.tool;import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
public class PinYin4jUtils {public static String getPinYin(String src) {char[] hz = src.toCharArray();String[] py;HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();format.setCaseType(HanyuPinyinCaseType.LOWERCASE);format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);format.setVCharType(HanyuPinyinVCharType.WITH_V);StringBuilder pys = new StringBuilder();int len = hz.length;try {for (int i = 0; i < len; i++) {if (Character.toString(hz[i]).matches("[\\u4E00-\\u9FA5]+")) {py = PinyinHelper.toHanyuPinyinStringArray(hz[i], format);pys.append(py[0]);} else {pys.append(hz[i]);}}} catch (BadHanyuPinyinOutputFormatCombination e) {e.printStackTrace();}return pys.toString();}public static String getPinYinHeadChar(String str) {StringBuilder convert = new StringBuilder();for (int i = 0; i < str.length(); i++) {char word = str.charAt(i);String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);if (pinyinArray != null) {convert.append(pinyinArray[0].charAt(0));} else {convert.append(word);}}return convert.toString().toUpperCase();}public static String getPinYinFirstHeadChar(String str) {String convert = "";String reg = "[^\u4e00-\u9fa5]";str = str.replaceAll(reg, "").replace(" ", "");if (str.length() > 0) {char word = str.charAt(0);String[] pinyinArray = PinyinHelper.toHanyuPinyinStringArray(word);if (pinyinArray != null) {convert += pinyinArray[0].charAt(0);} else {convert += word;}return convert.toUpperCase();} else {return "";}}public static String getCnASCII(String str) {StringBuilder buf = new StringBuilder();byte[] bGBK = str.getBytes();for (byte b : bGBK) {buf.append(Integer.toHexString(b & 0xff));}return buf.toString();}
}
8.PropertiesUtils.java
package com.sunxiansheng.tool;import lombok.extern.slf4j.Slf4j;import java.io.File;
import java.io.FileInputStream;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
@Slf4j
public class PropertiesUtils {private Map<String, Properties> propertiesMap = new HashMap<>();private Map<String, Long> modifyTimeMap = new HashMap<>();private String configPath = "";private PropertiesUtils() {}private static class SingleHolder {private static final PropertiesUtils INSTANCE = new PropertiesUtils();}public static PropertiesUtils getInstance() {return SingleHolder.INSTANCE;}public void configure(String path) {this.configPath = path;}public String getPropertyValue(String propertyFileName, String key) {String fileName = convertPropertiesFileName(propertyFileName);try {if (propertiesMap.get(fileName) == null) {loadProperties(fileName);} else {checkPropertiesFileModified(fileName);}return propertiesMap.get(fileName).getProperty(key);} catch (Exception e) {log.error("PropertiesUtils.getPropertyValue.error:{}", e.getMessage(), e);}return "";}private String convertPropertiesFileName(String propertyFileName) {String fileName = propertyFileName;if (fileName.endsWith(".properties")) {int index = fileName.lastIndexOf(".");fileName = fileName.substring(0, index);}return fileName;}private void loadProperties(String shortPropertyFileName) throws URISyntaxException {File file = getPropertiesFile(shortPropertyFileName);Long newTime = file.lastModified();if (propertiesMap.get(shortPropertyFileName) != null) {propertiesMap.remove(shortPropertyFileName);}Properties props = new Properties();try {props.load(new FileInputStream(file));} catch (Exception e) {log.error("PropertiesUtils.loadProperties.error:{}", e.getMessage(), e);}propertiesMap.put(shortPropertyFileName, props);modifyTimeMap.put(shortPropertyFileName, newTime);}private void checkPropertiesFileModified(String shortPropertyFileName) throws URISyntaxException {File file = getPropertiesFile(shortPropertyFileName);Long newTime = file.lastModified();Long lastModifiedTime = modifyTimeMap.get(shortPropertyFileName);if (newTime == 0) {if (lastModifiedTime == null) {log.error(shortPropertyFileName + ".properties file does not exist!");}} else if (newTime > lastModifiedTime) {loadProperties(shortPropertyFileName);}}private File getPropertiesFile(String shortPropertyFileName) throws URISyntaxException {File propertiesFile;if (this.configPath != null && !this.configPath.trim().isEmpty()) {return new File(this.configPath + File.separator + shortPropertyFileName + ".properties");}String dir = System.getProperty("user.dir") + File.separator + shortPropertyFileName + ".properties";propertiesFile = new File(dir);if (!propertiesFile.exists()) {URL url = PropertiesUtils.class.getResource("/" + shortPropertyFileName + ".properties");if (url == null) {propertiesFile = null;} else {propertiesFile = new File(url.toURI());}}return propertiesFile;}
}
9.SimpleDateFormatUtils.java
package com.sunxiansheng.tool;import java.text.SimpleDateFormat;
public class SimpleDateFormatUtils {private static final ThreadLocal<SimpleDateFormat> THREAD_LOCAL = new ThreadLocal<SimpleDateFormat>() {@Overrideprotected SimpleDateFormat initialValue() {return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");}};public static SimpleDateFormat getTime() {SimpleDateFormat simpleDateFormat = THREAD_LOCAL.get();if (simpleDateFormat == null) {return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");}return simpleDateFormat;}}
10.SpringContextUtils.java
package com.sunxiansheng.tool;import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.Map;
@Component
public class SpringContextUtils implements ApplicationContextAware {private static ApplicationContext applicationContext;@Overridepublic void setApplicationContext(ApplicationContext applicationContext) throws BeansException {this.applicationContext = applicationContext;}public static ApplicationContext getApplicationContext() {return applicationContext;}public static Object getBean(String name) throws BeansException {return applicationContext.getBean(name);}public static Object getBean(String name, Class requiredType) throws BeansException {return applicationContext.getBean(name, requiredType);}public static Object getBean(Class requiredType) throws BeansException {return applicationContext.getBean(requiredType);}public static <T> T getBeanByType(Class<T> clazz) {return applicationContext.getBean(clazz);}public static boolean containsBean(String name) {return applicationContext.containsBean(name);}public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {return applicationContext.isSingleton(name);}public static Class getType(String name) throws NoSuchBeanDefinitionException {return applicationContext.getType(name);}public static <T> Map<String, T> getBeanOfType(Class<T> clazz) throws NoSuchBeanDefinitionException {return applicationContext.getBeansOfType(clazz);}public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {return applicationContext.getAliases(name);}public static HttpServletRequest getHttpServletRequest() {return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();}public static HttpServletResponse getHttpServletResponse() {return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();}public static HttpSession getHttpSession() {HttpServletRequest request = getHttpServletRequest();return request.getSession();}
}
11.ThreadPoolUtils.java
package com.sunxiansheng.tool;import lombok.extern.slf4j.Slf4j;import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;
@Slf4j
public class ThreadPoolUtils {private ThreadPoolUtils() {}public static void shutdownPool(ExecutorService pool, int shutdownTimeout, int shutdownNowTimeout, TimeUnit timeUnit) {pool.shutdown();try {if (!pool.awaitTermination(shutdownTimeout, timeUnit)) {pool.shutdownNow();if (!pool.awaitTermination(shutdownNowTimeout, timeUnit)) {log.error("ThreadPoolUtils.shutdownPool.error");}}} catch (InterruptedException ie) {log.error("ThreadPoolUtils.shutdownPool.interrupted.error:{}", ie.getMessage(), ie);pool.shutdownNow();Thread.currentThread().interrupt();}}
}
12.UuidUtils.java
package com.sunxiansheng.tool;import java.util.UUID;
public class UuidUtils {public static String[] chars = new String[]{"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", "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"};public static String getUuid() {return UUID.randomUUID().toString();}public static String getUuid32() {return UUID.randomUUID().toString().replace("-", "");}public static String getUuid8() {StringBuilder shortBuffer = new StringBuilder();String uuid = UUID.randomUUID().toString().replace("-", "");for (int i = 0; i < 8; i++) {String str = uuid.substring(i * 4, i * 4 + 4);int x = Integer.parseInt(str, 16);shortBuffer.append(chars[x % 62]);}return shortBuffer.toString();}
}