BeanHelper
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
@Slf4j
public class BeanHelper {
public static <T> T copyProperties(Object source, Class<T> target){
try {
T t = target.newInstance();
BeanUtils.copyProperties(source, t);
return t;
} catch (Exception e) {
log.error("【数据转换】数据转换出错,目标对象{}构造函数异常", target.getName(), e);
}
}
public static <T> List<T> copyWithCollection(List<?> sourceList, Class<T> target){
try {
return sourceList.stream().map(s -> copyProperties(s, target)).collect(Collectors.toList());
} catch (Exception e) {
log.error("【数据转换】数据转换出错,目标对象{}构造函数异常", target.getName(), e);
}
}
public static <T> Set<T> copyWithCollection(Set<?> sourceList, Class<T> target){
try {
return sourceList.stream().map(s -> copyProperties(s, target)).collect(Collectors.toSet());
} catch (Exception e) {
log.error("【数据转换】数据转换出错,目标对象{}构造函数异常", target.getName(), e);
}
}
}
CookieUtils
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
@Slf4j
public final class CookieUtils {
public static String getCookieValue(HttpServletRequest request, String cookieName) {
return getCookieValue(request, cookieName, null);
}
public static String getCookieValue(HttpServletRequest request, String cookieName, String charset) {
Cookie[] cookieList = request.getCookies();
if (cookieList == null || cookieName == null) {
return null;
}
String retValue = null;
try {
for (int i = 0; i < cookieList.length; i++) {
if (cookieList[i].getName().equals(cookieName)) {
if (charset != null && charset.length() > 0) {
retValue = URLDecoder.decode(cookieList[i].getValue(), charset);
} else {
retValue = cookieList[i].getValue();
}
break;
}
}
} catch (UnsupportedEncodingException e) {
log.error("Cookie Decode Error.", e);
}
return retValue;
}
public static CookieBuilder newCookieBuilder() {
return new CookieBuilder();
}
public static void deleteCookie(String cookieName, String domain,HttpServletResponse response) {
Cookie cookie = new Cookie(cookieName, "");
cookie.setMaxAge(0);
cookie.setPath("/");
cookie.setDomain(domain);
response.addCookie(cookie);
}
public static class CookieBuilder {
private HttpServletRequest request;
private HttpServletResponse response;
private Integer maxAge;
private String charset;
private boolean httpOnly = false;
private String domain;
private String path = "/";
private String name;
private String value;
public CookieBuilder() {
}
public CookieBuilder request(HttpServletRequest request) {
this.request = request;
return this;
}
public CookieBuilder response(HttpServletResponse response) {
this.response = response;
return this;
}
public CookieBuilder maxAge(int maxAge) {
this.maxAge = maxAge;
return this;
}
public CookieBuilder charset(String charset) {
this.charset = charset;
return this;
}
public CookieBuilder domain(String domain) {
this.domain = domain;
return this;
}
public CookieBuilder path(String path) {
this.path = path;
return this;
}
public CookieBuilder value(String value) {
this.value = value;
return this;
}
public CookieBuilder name(String name) {
this.name = name;
return this;
}
public CookieBuilder httpOnly(boolean httpOnly) {
this.httpOnly = httpOnly;
return this;
}
public void build() {
try {
if (StringUtils.isBlank(charset)) {
charset = "utf-8";
}
if(StringUtils.isBlank(name)||StringUtils.isBlank(value)){
throw new RuntimeException("cookie名称和值不能为空!");
}
if (StringUtils.isNotBlank(charset)) {
value = URLEncoder.encode(value, charset);
}
Cookie cookie = new Cookie(name, value);
if (maxAge != null && maxAge >= 0)
cookie.setMaxAge(maxAge);
if(StringUtils.isNotBlank(domain)){
cookie.setDomain(domain);
}else if (null != request) {
cookie.setDomain(getDomainName(request));
}
cookie.setPath("/");
if(StringUtils.isNotBlank(path)){
cookie.setPath(path);
}
cookie.setHttpOnly(httpOnly);
response.addCookie(cookie);
} catch (Exception e) {
log.error("Cookie Encode Error.", e);
}
}
private String getDomainName(HttpServletRequest request) {
String domainName = null;
String serverName = request.getRequestURL().toString();
if (serverName == null || serverName.equals("")) {
domainName = "";
} else {
serverName = serverName.toLowerCase();
serverName = serverName.substring(7);
final int end = serverName.indexOf("/");
serverName = serverName.substring(0, end);
final String[] domains = serverName.split("\\.");
int len = domains.length;
if (len > 3) {
domainName = domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
} else if (len <= 3 && len > 1) {
domainName = domains[len - 2] + "." + domains[len - 1];
} else {
domainName = serverName;
}
}
if (domainName != null && domainName.indexOf(":") > 0) {
String[] ary = domainName.split("\\:");
domainName = ary[0];
}
return domainName;
}
}
}
IdWorker
import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.net.NetworkInterface;
public class IdWorker {
private final static long twepoch = 1288834974657L;
private final static long workerIdBits = 5L;
private final static long datacenterIdBits = 5L;
private final static long maxWorkerId = -1L ^ (-1L << workerIdBits);
private final static long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
private final static long sequenceBits = 12L;
private final static long workerIdShift = sequenceBits;
private final static long datacenterIdShift = sequenceBits + workerIdBits;
private final static long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
private final static long sequenceMask = -1L ^ (-1L << sequenceBits);
private static long lastTimestamp = -1L;
private long sequence = 0L;
private final long workerId;
private final long datacenterId;
public IdWorker(){
this.datacenterId = getDatacenterId(maxDatacenterId);
this.workerId = getMaxWorkerId(datacenterId, maxWorkerId);
}
public IdWorker(long workerId, long datacenterId) {
if (workerId > maxWorkerId || workerId < 0) {
throw new IllegalArgumentException(String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
}
if (datacenterId > maxDatacenterId || datacenterId < 0) {
throw new IllegalArgumentException(String.format("datacenter Id can't be greater than %d or less than 0", maxDatacenterId));
}
this.workerId = workerId;
this.datacenterId = datacenterId;
}
public synchronized long nextId() {
long timestamp = timeGen();
if (timestamp < lastTimestamp) {
throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
}
if (lastTimestamp == timestamp) {
sequence = (sequence + 1) & sequenceMask;
if (sequence == 0) {
timestamp = tilNextMillis(lastTimestamp);
}
} else {
sequence = 0L;
}
lastTimestamp = timestamp;
long nextId = ((timestamp - twepoch) << timestampLeftShift)
| (datacenterId << datacenterIdShift)
| (workerId << workerIdShift) | sequence;
return nextId;
}
private long tilNextMillis(final long lastTimestamp) {
long timestamp = this.timeGen();
while (timestamp <= lastTimestamp) {
timestamp = this.timeGen();
}
return timestamp;
}
private long timeGen() {
return System.currentTimeMillis();
}
protected static long getMaxWorkerId(long datacenterId, long maxWorkerId) {
StringBuffer mpid = new StringBuffer();
mpid.append(datacenterId);
String name = ManagementFactory.getRuntimeMXBean().getName();
if (!name.isEmpty()) {
mpid.append(name.split("@")[0]);
}
return (mpid.toString().hashCode() & 0xffff) % (maxWorkerId + 1);
}
protected static long getDatacenterId(long maxDatacenterId) {
long id = 0L;
try {
InetAddress ip = InetAddress.getLocalHost();
NetworkInterface network = NetworkInterface.getByInetAddress(ip);
if (network == null) {
id = 1L;
} else {
byte[] mac = network.getHardwareAddress();
id = ((0x000000FF & (long) mac[mac.length - 1])
| (0x0000FF00 & (((long) mac[mac.length - 2]) << 8))) >> 6;
id = id % (maxDatacenterId + 1);
}
} catch (Exception e) {
System.out.println(" getDatacenterId: " + e.getMessage());
}
return id;
}
}
JsonUtils
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.List;
import java.util.Map;
public class JsonUtils {
public static final ObjectMapper mapper = new ObjectMapper();
private static final Logger logger = LoggerFactory.getLogger(JsonUtils.class);
public static String toString(Object obj) {
if (obj == null) {
return null;
}
if (obj.getClass() == String.class) {
return (String) obj;
}
try {
return mapper.writeValueAsString(obj);
} catch (JsonProcessingException e) {
logger.error("json序列化出错:" + obj, e);
return null;
}
}
public static <T> T toBean(String json, Class<T> tClass) {
try {
return mapper.readValue(json, tClass);
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
public static <E> List<E> toList(String json, Class<E> eClass) {
try {
return mapper.readValue(json, mapper.getTypeFactory().constructCollectionType(List.class, eClass));
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
public static <K, V> Map<K, V> toMap(String json, Class<K> kClass, Class<V> vClass) {
try {
return mapper.readValue(json, mapper.getTypeFactory().constructMapType(Map.class, kClass, vClass));
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
public static <T> T nativeRead(String json, TypeReference<T> type) {
try {
return mapper.readValue(json, type);
} catch (IOException e) {
logger.error("json解析出错:" + json, e);
return null;
}
}
}
RegexPatterns
public abstract class RegexPatterns {
public static final String PHONE_REGEX = "^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\\d{8}$";
public static final String EMAIL_REGEX = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";
public static final String USERNAME_REGEX = "^\\w{4,32}$";
}
RegexUtils
import org.apache.commons.lang3.StringUtils;
public class RegexUtils {
public static boolean isPhone(String phone){
return matches(phone, RegexPatterns.PHONE_REGEX);
}
public static boolean isEmail(String email){
return matches(email, RegexPatterns.EMAIL_REGEX);
}
private static boolean matches(String str, String regex){
if (StringUtils.isBlank(str)) {
return false;
}
return str.matches(regex);
}
}