文章目录
- https://tool.lu/
- 文件操作-目录、文件等
- IPV4 类型判断、格式转化工具类
- Json 序列化、反系列化
- StringUtils
- BooleanUtils.isTrue(null)==false
- ListUtils\Maputils 结合 lamada
- 不可变Map对象 Collections.unmodifiableMap
- 默认返回空集合
- Optional.ofNullable(list).orElse 和 Optional.of(list)
- Guava 工具类
- 时间工具类
- 非对称加密验签工具类
- 非对称加密基础工具类
- CloseResourceUtils 关闭IO资源
- BrowserInfoUtils 浏览器信息
- HttpURLConnectionUtils
- IPAddrUtils 获取ip地址+ip解析为地址
- SystemInfoUtils 操作系统信息
- 生成8位随机密码
- 音频文件格式在线转化
- 在线工具箱
- 自动替换字符串工具类
https://tool.lu/
文件操作-目录、文件等
IPV4 类型判断、格式转化工具类
输入 127.0.0.1 判断为哪一类地址(A-E),转化为long,或者二进制格式
网络相关积累-基于IPV4-4、IPV4 地址格式转化、类型判断工具类
Json 序列化、反系列化
Gson\FastJson\Jackson
Gson
<guava.version>18.0</guava.version>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>${gson.version}</version>
</dependency>
import lombok.experimental.UtilityClass;
import com.google.gson.*;
import java.util.ArrayList;
import java.util.List;
/**
* @Title:Json 序列化/反序列化工具类-Gson 优先推荐使用
* @Description: 用于日志打印等场景
* <p>
* 运用反射机制,只关注有什么属性
* </p>
* @Version: v1.0
* @Updatedby:
*/
@UtilityClass
public class GsonUtils {
private final Gson GSON = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
public String toJson(Object obj) {
return GSON.toJson(obj);
}
public <T> T fromJson(String values, Class<T> cls) {
return GSON.fromJson(values, cls);
}
public <T> List<T> fromListJson(String values, Class<T> cls) {
List<T> list = new ArrayList();
JsonArray array = new JsonParser().parse(values).getAsJsonArray();
for (JsonElement jsonElement : array) {
list.add(GSON.fromJson(jsonElement, cls));
}
return list;
}
public static void main(String[] args) {
AClass aClass = new AClass();
aClass.name = "jecket";
aClass.age = "100";
System.out.println(GsonUtils.toJson(aClass));
String tem = GsonUtils.toJson(aClass);
AClass b = GsonUtils.fromJson(tem, AClass.class);
System.out.println(GsonUtils.toJson(b));
}
private static class AClass{
String name;
String age;
public String getName(){
return this.name;
}
public String getA(){
return "aaa-1";
}
public String isA(){
return "aaa-2";
}
}
}
FastJson
<fastjson.version>1.2.54</fastjson.version>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>${fastjson.version}</version>
</dependency>
import com.alibaba.fastjson.JSON;
import lombok.experimental.UtilityClass;
/**
* @Title:Json 序列化/反序列化工具类-FastJson
* @Description: 用于日志打印等场景
* @Version: v1.0
* @Updatedby:
*/
@UtilityClass
public class FastJsonUtils {
public String toJson(Object obj) {
return JSON.toJSONString(obj);
}
public <T> T fromJson(String values, Class<T> cls) {
return JSON.parseObject(values,cls);
}
public static void main(String[] args) {
AClass aClass = new AClass();
aClass.name = "jecket";
aClass.age = "100";
System.out.println(GsonUtils.toJson(aClass));
String tem = GsonUtils.toJson(aClass);
AClass b = GsonUtils.fromJson(tem, AClass.class);
System.out.println(GsonUtils.toJson(b));
}
private static class AClass{
String name;
String age;
public String getName(){
return this.name;
}
public String getA(){
return "aaa-1";
}
public String isA(){
return "aaa-2";
}
}
}
Jackson -避免普通方法get/is开头,避免序列化时勿调用
<jackson-databind.version>2.10.1</jackson-databind.version>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-databind.version}</version>
</dependency>
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.experimental.UtilityClass;
import org.apache.commons.lang3.StringUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @Title:Json 序列化/反序列化工具类-Jackson
* @Description: 用于日志打印等场景
* <p>
* 序列化借助 get/is 方法。普通方法避免用get/is开头,防止被勿调用
* <br>
* 反序列化借助于 set 方法,非属性赋值方法,避免 set 开头
* </p>
* @Version: v1.0
* @Updatedby:
*/
@UtilityClass
public class JacksonUtils {
private static final ObjectMapper mapper = new ObjectMapper();
static {
//序列化时,跳过null属性
mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
//序列化时,遇到空bean(无属性)时不会失败
mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
//反序列化时,遇到未知属性(在bean上找不到对应属性)时不会失败
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
//反序列化时,将空数组([])当做null来处理(以便把空数组反序列化到对象属性上——对php生成的json的map属性很有用)
mapper.configure(DeserializationFeature.ACCEPT_EMPTY_ARRAY_AS_NULL_OBJECT, true);
//不通过fields来探测(仅通过标准getter探测)
mapper.configure(MapperFeature.AUTO_DETECT_FIELDS, false);
}
public String toJsonString(Object obj) throws JsonProcessingException {
if (obj == null) {
return "";
}
return mapper.writeValueAsString(obj);
}
public <T> T parseSimpleObject(String jsonString, Class<T> clazz) throws IOException {
if (StringUtils.isBlank(jsonString)) {
return null;
}
return mapper.readValue(jsonString, clazz);
}
public <T> T parseObject(String jsonString, TypeReference<T> typeReference) throws IOException {
if (StringUtils.isBlank(jsonString)) {
return null;
}
return mapper.readValue(jsonString, typeReference);
}
public <T> List<T> jsonStringToList(String jsonString) throws IOException {
if (StringUtils.isBlank(jsonString)) {
return new ArrayList<>(4);
}
return mapper.readValue(jsonString, new TypeReference<List<T>>(){});
}
public <K, V> Map<K, V> jsonStringToMap(String jsonString) throws IOException {
if (StringUtils.isBlank(jsonString)) {
return new HashMap<>(4);
}
return mapper.readValue(jsonString, new TypeReference<Map<K, V>>(){});
}
public <K, V> List<Map<K, V>> jsonStringToMapList(String jsonString) throws IOException {
if (StringUtils.isBlank(jsonString)) {
return new ArrayList<>(4);
}
return mapper.readValue(jsonString, new TypeReference<List<Map<K, V>>>(){});
}
public static void main(String[] args) throws JsonProcessingException {
AClass aClass = new AClass();
aClass.name="jecket";
aClass.age="100";
aClass.flag=true;
System.out.println(JacksonUtils.toJsonString(aClass));
}
private static class AClass{
String name;
String age;
boolean flag;
public boolean isFlag(){
return this.flag;
}
public boolean getFlag(){
return this.flag;
}
public String getName(){
return this.name;
}
public String getA(){
return "aaa-1";
}
public boolean isA(){
return true;
}
}
}
StringUtils
BooleanUtils.isTrue(null)==false
·maven
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.12.0</version>
</dependency>
·java
@Test
public void test2(){
boolean result = BooleanUtils.isTrue(null);
System.out.println(result);
}
ListUtils\Maputils 结合 lamada
·maven 依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-collections4</artifactId>
<version>4.4</version>
</dependency>
·java
import org.apache.commons.collections4.ListUtils;
@Test
public void test(){
List<Integer> list = Lists.newArrayList(1,2,3,4,5);
Integer value1 = ListUtils.emptyIfNull(list).stream().findFirst().get();
}
@Test
public void testh(){
List<Integer> list1 = null;
//可以避免空指针
List<Integer> list2 = ListUtils.emptyIfNull(list1).stream().collect(Collectors.toList());
System.out.println(list2);//[]
}
@Test
public void testi(){
Map<Long,String> map = null;
//可以避免空指针
Map<Long,String> map2 = MapUtils.emptyIfNull(map);
System.out.println(map2);{}
}
不可变Map对象 Collections.unmodifiableMap
Collections.unmodifiableMap(map对象)
默认返回空集合
但是注意,这个空集合虽然不是null,即 Collections.isEmpty() 为fa;se,但是它是Collections类里的静态内部类,在继承AbstractList后并没有实现add()、remove()等方法,故不可使用 add 和 remove 放法
if(MapUtils.isEmpty(demoList)){
return Collections.emptyList();
}
Optional.ofNullable(list).orElse 和 Optional.of(list)
Optional.ofNullable 可以避免空指针,会强制 orElse
@Test
public void testa(){
List list = null;
//List listRight = Optional.ofNullable(list).orElse(Lists.newArrayList(1,2,3));
List listRight = Optional.ofNullable(list).orElse(Lists.newArrayList(1,2,3));
System.out.println("Optional.ofNullable 可以避免空指针,会强制 orElse"+listRight);
List listNullPointerException = Optional.of(list).orElse(Lists.newArrayList(1,2,3));
System.out.println("Optional.of(null)orElse(new 对象) 无法避免空指针 NullPointerException,运行时就报错");
}
Guava 工具类
- Maven 依赖
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>
本地缓存
- 工具类和测试方法
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheLoader;
import com.google.common.cache.LoadingCache;
import com.google.common.collect.Lists;
import lombok.SneakyThrows;
import org.mortbay.util.ajax.JSON;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
* @Title:
* @Description:
* @Updatedby:
*/
public class GuavaCacheUtil {
/**
* 获得本地缓存
*
* @param id
* @return
*/
public static List<String> getListCacheExpireAfterAccess(Long id) throws ExecutionException {
return localingCacheExpireAfterAccess.get(id);
}
/**
* 每次调用设置5秒的有效期
*/
private static LoadingCache<Long, List<String>> localingCacheExpireAfterAccess =
CacheBuilder.newBuilder().expireAfterAccess(5, TimeUnit.SECONDS).build(new CacheLoader<Long, List<String>>(){
@Override
public List<String> load(Long id) throws Exception {
System.out.println("更新缓存,5秒后清除缓存:"+System.currentTimeMillis());
List<String> list = Lists.newArrayList("111"+id,"222"+id,"333"+id);
return list;
}
});
/**
* 获得本地缓存
* 消息失效,只允许一个请求,其余先返回旧值
*
* @param id
* @return
*/
public static List<String> getListCacheRefreshAfterWrite(Long id) throws ExecutionException {
return localingCacheRefreshAfterWrite.get(id);
}
/**
* 每次调用设置5秒的有效期
*/
private static LoadingCache<Long, List<String>> localingCacheRefreshAfterWrite =
CacheBuilder.newBuilder().refreshAfterWrite(3, TimeUnit.SECONDS).build(new CacheLoader<Long, List<String>>() {
@Override
public List<String> load(Long id) throws Exception {
System.out.println("更新缓存-开始:" + System.currentTimeMillis());
List<String> list = Lists.newArrayList("111" + id, "222" + id, "333" + id + System.currentTimeMillis());
Thread.sleep(1000 * 2);
System.out.println("更新缓存-结束,3秒后清除缓存:" + System.currentTimeMillis());
return list;
}
});
}
- 测试方法
public static void main(String[] args) throws ExecutionException, InterruptedException {
GuavaCacheUtil.testLocalingCacheExpireAfterAccess();
GuavaCacheUtil.testGetListCacheRefreshAfterWrite();
}
/**
更新缓存,5秒后清除缓存:1608629304383
["1111","2221","3331"]
["1111","2221","3331"]
等待6秒,届时缓存失效
更新缓存,5秒后清除缓存:1608629310391
["1111","2221","3331"]
* @throws ExecutionException
* @throws InterruptedException
*/
public static void testLocalingCacheExpireAfterAccess() throws ExecutionException, InterruptedException {
List<String> list = GuavaCacheUtil.getListCacheExpireAfterAccess(1L);
System.out.println(JSON.toString(list));
List<String> list2 = GuavaCacheUtil.getListCacheExpireAfterAccess(1L);
System.out.println(JSON.toString(list2));
System.out.println("等待6秒,届时缓存失效");
Thread.sleep(1000 * 6);
List<String> list3 = GuavaCacheUtil.getListCacheExpireAfterAccess(1L);
System.out.println(JSON.toString(list3));
}
public static void testGetListCacheRefreshAfterWrite() throws ExecutionException, InterruptedException {
List<String> list = GuavaCacheUtil.getListCacheRefreshAfterWrite(1L);
System.out.println(JSON.toString(list));
List<String> list2 = GuavaCacheUtil.getListCacheRefreshAfterWrite(1L);
System.out.println(JSON.toString(list2));
System.out.println("等待4秒,届时缓存失效");
Thread.sleep(1000 * 4);
//缓存设置3秒失效,等待了4秒,故失效,使用两个线程进行查询,预期结果第一个阻塞,第二个立即返回历史值
Thread t1= new Thread(){
@SneakyThrows
@Override
public synchronized void start() {
super.start();
List<String> list = GuavaCacheUtil.getListCacheRefreshAfterWrite(1L);
System.out.println("t1"+JSON.toString(list));
}
};
Thread t2= new Thread(){
@SneakyThrows
@Override
public synchronized void start() {
super.start();
List<String> list = GuavaCacheUtil.getListCacheRefreshAfterWrite(1L);
System.out.println("t2:"+JSON.toString(list));
}
};
t1.start();
t2.start();
}
校验
Guava 本身不单单支持本地缓存,更多其它用法可以参考 https://www.jianshu.com/p/1c49cfa72f94
- IllegalArgumentException
import com.google.common.base.Preconditions;
import org.junit.jupiter.api.Test;
public class DelTest {
@Test
public void test1() throws Exception{
Preconditions.checkArgument(1<0,"参数校验不通过");
}
}
时间工具类
更多信息请查看 Lambda 时间相关 积累
现成
maven
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.11</version>
</dependency>
org.apache.commons.lang3.time.DateUtils
需要 Java 8
import lombok.experimental.UtilityClass;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Objects;
import java.util.regex.Pattern;
@UtilityClass
public class DateUtils {
public static final String TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
public static final String DATE_PATTERN = "yyyy-MM-dd";
public static final String CN_PATTERN = "yyyy年MM月dd日";
private static DateTimeFormatter formatter2 = DateTimeFormatter.ofPattern(DATE_PATTERN);
/**
* 检查字符串格式符合 yyyy-MM-dd
*
* @param checkdDate
* @return
*/
public boolean checkDate(String checkdDate) {
Pattern pattern = Pattern.compile("" +
"(^[0-9]{4}([-]{1})[0-9]{2}([-]{1})[0-9]{2}$)");
return pattern.matcher(checkdDate).matches();
}
/**
* 判断入参字符串对应日期是否为 今天(不含今天)以后
*
* @param yyyyMMdd 格式为 yyyy-MM-dd
* @return
*/
public boolean isAfterToday(String yyyyMMdd) {
if (!checkDate(yyyyMMdd)) {
return false;
}
String[] dates = yyyyMMdd.split("-");
LocalDate checkDate = LocalDate.of(Integer.valueOf(dates[0]), Integer.valueOf(dates[1]), Integer.valueOf(dates[2]));
return checkDate.isAfter(LocalDate.now());
}
/**
* 判断 A<=B
*
* @param A 格式 yyyy-MM-dd
* @param B 格式 yyyy-MM-dd
* @return
*/
public static boolean bAfterOrEqualThenA(String A, String B) {
if (!checkDate(A) || !checkDate(B)) {
return false;
}
if (B.equals(A)) {
return true;
}
String[] datesA = A.split("-");
LocalDate checkDateA = LocalDate.of(Integer.valueOf(datesA[0]), Integer.valueOf(datesA[1]), Integer.valueOf(datesA[2]));
String[] datesB = B.split("-");
LocalDate checkDateB = LocalDate.of(Integer.valueOf(datesB[0]), Integer.valueOf(datesB[1]), Integer.valueOf(datesB[2]));
return checkDateB.isAfter(checkDateA);
}
/**
* 字符串转 LocalDate ,字符串格式需要为yyyy-MM-dd
*
* @param yyyyMMdd
* @return
*/
public LocalDate getLocalDateFromStr(String yyyyMMdd) {
return LocalDate.parse(yyyyMMdd, formatter2);
}
/**
* 今天 yyyy-MM-dd 00:00:00 的时间戳
*
* @return
*/
public static Long getTodayStartMillisecond() {
return LocalDate.now().atStartOfDay().toEpochSecond(ZoneOffset.of("+8")) * 1000;
}
/**
* 时间格式化
*
* @param time
* @param patten
* @return
*/
public static String timeToStr(Long time, String patten) {
SimpleDateFormat format = new SimpleDateFormat(patten);
String str = format.format(time);
return str;
}
/**
* 昨天 yyyy-MM-dd 00:00:00 的时间戳
*
* @return
*/
public static Long getYesterdayStartMillisecond() {
return LocalDate.now().minusDays(1).atStartOfDay().toEpochSecond(ZoneOffset.of("+8")) * 1000;
}
/**
* 时间戳转 LocalDate
*
* @param datestamp
* @return
*/
public static LocalDate getLocalDateByTimeStamp(Long datestamp) {
Long sencond = datestamp / 1000;
return LocalDateTime.ofEpochSecond(sencond, 0, ZoneOffset.of("+8")).toLocalDate();
}
/**
* 将 LocalDate 格式时间转化为字符串
*
* @param localDate
* @return
*/
public static String localDateToStringByDefaultPattern(LocalDate localDate) {
return localDate.format(formatter2);
}
/**
* 获取 LocalDate 毫秒时间戳
*
* @param localDateTime
* @return
*/
public static Long getTimeStampOfLocalDateTime(LocalDateTime localDateTime) {
if (Objects.isNull(localDateTime)) {
return 0L;
}
return localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
}
/**
* 获取 LocalDate 毫秒时间戳
*
* @param localDate
* @return
*/
public static Long getTimeStampOfLocalDate(LocalDate localDate) {
if (Objects.isNull(localDate)) {
return 0L;
}
return localDate.atStartOfDay().toEpochSecond(ZoneOffset.of("+8")) * 1000;
}
/**
* 获取 今天+n 天 对应的 localDate
*
* @param n 正数、零、负数
* @return
*/
public static LocalDate getLocalDateTodayPlusN(int n) {
return LocalDate.now(ZoneId.of("+8")).plusDays(n);
}
/**
* 获取毫秒时间戳
*
* @param localDate
* @return
*/
public static Long getTimeStameMillisecond(LocalDate localDate) {
return localDate.atStartOfDay().toEpochSecond(ZoneOffset.of("+8")) * 1000;
}
/**
* 获取当前时间 LocalDateTime
* @return
*/
public static LocalDateTime getNowLocalDateTime(){
return LocalDateTime.now(ZoneId.of("+8"));
}
public static LocalDateTime getLocalDateTimeByTimestamp(Long timestamp){
if(Objects.isNull(timestamp) || timestamp.longValue()<=0){
return null;
}
return Instant.ofEpochMilli(timestamp).atOffset(ZoneOffset.of("+8")).toLocalDateTime();
}
public static long getLongByLocaldateTime(LocalDateTime localDateTime){
if(Objects.isNull(localDateTime)){
return getLongByLocaldateTime(getNowLocalDateTime());
}
return localDateTime.toInstant(ZoneOffset.of("+8")).toEpochMilli();
}
}
非对称加密验签工具类
支持 SHA1withRSA、SHA256withRSA、SHA1withDSA
本类需要工具类支持:https://mp.csdn.net/mdeditor/84635754 非对称加密基础工具类
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.SignatureException;
import java.security.spec.InvalidKeySpecException;
import org.apache.commons.codec.binary.Base64;
/**
* 非对称加密验签工具类
* jie.wu
* 本类需要工具类支持:https://mp.csdn.net/mdeditor/84635754 非对称加密基础工具类
* /
public class SignatureUtil {
//下面提供一个 SHA1withRSA 的签名和验证例子
public static void main(String[] args) throws NoSuchAlgorithmException, InvalidKeySpecException, InvalidKeyException, SignatureException, UnsupportedEncodingException {
//RSA 1024 私钥
String privateBase64Str="MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALfXBP15PeOBS0h20hXZtIyeKiWx9py+VWagxfY2QvWH/+wu8xMpt0WFNWG6nS3ju9u2cViRQUYjRD5kz8hpRy8NdVoV/kbkZeK3LUqZs5/cb378uQTO3LWfOQJFBMz6ll2CXWEjEHGdxzj6iRjFYoC4VS+DDTGO+6iHmYSpP3/1AgMBAAECgYB94VqGYZ1yCZdOACZsVczeOHLtqsUNoPqDMnU62P7SdxRTWfaRWZAnp0XdLFXyFS0ODgfguF10tDNHceog9Y2KS3fHJK3JIur1Y55BqKzLlQlrAWpziaigEw+xJqiO+U67gomlCLTS6kYhFvPGXip3wOctvEh8yG1RX3exTmiVwQJBAPlWm6Aok86vHsBS8Znev1VV9nsSexrJXXkkdHv2ux2JSwQi/WNwWloolUtHFCGcyVmhNEmB7sSbR7/hmaKhiNECQQC8wGySaQIessawFnN/i+xmdoO0OeLCaR9MEce3B5dfRlTq37cfCbGCGnhSi5iRzx4/PHJGNoLPP2xFTVZ5VY3lAkA2rsTgwiVwbb2bxlUQPubNa1XsNehjvofOeq1FRp5Q4vxdwuK5fTmDjmT3pnYGzSDnlFAoUuOvoLKCpZKRNUYRAkALj4WW2hOlKbH9qwJb94f9JpkeesUmvyWJlTU0QqTE0xv0XstqfT+ABnsEI0Su+Y6StPMS1dfhNbM982Sufcz5AkB8OC1vMSQ0oYKxgS3nvNyNlTEjcveJALQAgU7vpSiA0/5LdwUFb7gCKQDL6pq8ySbZ4NV/U5xDVoBzsa5AIEVK";
//RSA 1024 公钥
String publicBase64Str="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC31wT9eT3jgUtIdtIV2bSMniolsfacvlVmoMX2NkL1h//sLvMTKbdFhTVhup0t47vbtnFYkUFGI0Q+ZM/IaUcvDXVaFf5G5GXity1KmbOf3G9+/LkEzty1nzkCRQTM+pZdgl1hIxBxncc4+okYxWKAuFUvgw0xjvuoh5mEqT9/9QIDAQAB";
//非对称加密算法,如 RSA
String algorithm="RSA";
//非对称加密验签规则
String sign_algorithm="SHA1withRSA";
//待加密字符串:
String str="method=info.auth#app_id=2138&sign_type=RSA×tamp=2013-01-0108:08:08";
//字符编码 方式
String charset="utf8";
//获取私钥
PrivateKey privateKey=AsymmetricEncryptionUtil.restorePrivateKey(privateBase64Str,algorithm,charset);
//获取公钥
PublicKey publicKey=AsymmetricEncryptionUtil.restorePublicKey(publicBase64Str,algorithm,charset);
//使用私钥计算签名
String signStr=signatureSign(sign_algorithm,charset,str,privateKey);
System.out.println("signStr="+signStr);
//使用公钥验证签名
System.out.println(signatureVerify(sign_algorithm,charset,str,signStr,publicKey));
}
/**
* 非对称加密签名-签名计算方法
* @param algorithm 签名算法,如 SHA1withRSA
* <ul>
* <li>{@code SHA1withDSA}</li>
* <li>{@code SHA1withRSA}</li>
* <li>{@code SHA256withRSA}</li>
* </ul>
* @param charset 字符编码格式,如 utf8、gbk
* @param str 原字符串
* @param privateKey 非对称加密 私钥
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws SignatureException
* @throws UnsupportedEncodingException
*/
public static String signatureSign(String algorithm,String charset,String str,PrivateKey privateKey) throws NoSuchAlgorithmException, InvalidKeyException, SignatureException, UnsupportedEncodingException {
//指定签名算法如 SHA1withRSA
Signature signature = Signature.getInstance(algorithm);
signature.initSign(privateKey);
//注意编码格式 utf8、gbk
signature.update(str.getBytes(charset));
//结果转 Base64,注意编码格式 utf8、gbk
String signStr=new String(Base64.encodeBase64(signature.sign()),charset);
return signStr;
}
/**
* 非对称加密签名-签名校验方法,验证通过返回 true
* @param algorithm 签名算法,如 SHA1withRSA
* <ul>
* <li>{@code SHA1withDSA}</li>
* <li>{@code SHA1withRSA}</li>
* <li>{@code SHA256withRSA}</li>
* </ul>
* @param charset 字符编码格式,如 utf8、gbk
* @param str 原字符串
* @param signStr 待校验签名内容
* @param publicKey 非对称加密 公钥
* @return
* @throws InvalidKeyException
* @throws NoSuchAlgorithmException
* @throws SignatureException
* @throws UnsupportedEncodingException
*/
public static boolean signatureVerify(String algorithm,String charset,String str,String signStr,PublicKey publicKey) throws InvalidKeyException, NoSuchAlgorithmException, SignatureException, UnsupportedEncodingException {
//指定签名算法如 SHA1withRSA
Signature signature = Signature.getInstance(algorithm);
signature.initVerify(publicKey);
//加密前的文本
signature.update(str.getBytes(charset));
//比较 私钥 的加密结果
return signature.verify(Base64.decodeBase64(signStr.getBytes()));
}
}
非对称加密基础工具类
可以根据不同的入参,支持 RSA\DSA等非对称加密算法
import org.apache.commons.codec.binary.Base64;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import java.io.UnsupportedEncodingException;
import java.security.*;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;
/**
* 非对称加密 工具类
* jie.wu
*/
public class AsymmetricEncryptionUtil {
public static void main(String [] args) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException {
//算法名称
String algorithm="RSA";
//私钥长度
int keySize=1024;
//待加密字符串
String str="123456789abc";
//编码格式
String charset="utf8";
//base64 格式的RSA 1024 私钥
String privateKeyBase64="MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBALfXBP15PeOBS0h20hXZtIyeKiWx9py+VWagxfY2QvWH/+wu8xMpt0WFNWG6nS3ju9u2cViRQUYjRD5kz8hpRy8NdVoV/kbkZeK3LUqZs5/cb378uQTO3LWfOQJFBMz6ll2CXWEjEHGdxzj6iRjFYoC4VS+DDTGO+6iHmYSpP3/1AgMBAAECgYB94VqGYZ1yCZdOACZsVczeOHLtqsUNoPqDMnU62P7SdxRTWfaRWZAnp0XdLFXyFS0ODgfguF10tDNHceog9Y2KS3fHJK3JIur1Y55BqKzLlQlrAWpziaigEw+xJqiO+U67gomlCLTS6kYhFvPGXip3wOctvEh8yG1RX3exTmiVwQJBAPlWm6Aok86vHsBS8Znev1VV9nsSexrJXXkkdHv2ux2JSwQi/WNwWloolUtHFCGcyVmhNEmB7sSbR7/hmaKhiNECQQC8wGySaQIessawFnN/i+xmdoO0OeLCaR9MEce3B5dfRlTq37cfCbGCGnhSi5iRzx4/PHJGNoLPP2xFTVZ5VY3lAkA2rsTgwiVwbb2bxlUQPubNa1XsNehjvofOeq1FRp5Q4vxdwuK5fTmDjmT3pnYGzSDnlFAoUuOvoLKCpZKRNUYRAkALj4WW2hOlKbH9qwJb94f9JpkeesUmvyWJlTU0QqTE0xv0XstqfT+ABnsEI0Su+Y6StPMS1dfhNbM982Sufcz5AkB8OC1vMSQ0oYKxgS3nvNyNlTEjcveJALQAgU7vpSiA0/5LdwUFb7gCKQDL6pq8ySbZ4NV/U5xDVoBzsa5AIEVK";
//base64 格式的 RSA 1024 公钥
String publicKeyBase64="MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQC31wT9eT3jgUtIdtIV2bSMniolsfacvlVmoMX2NkL1h//sLvMTKbdFhTVhup0t47vbtnFYkUFGI0Q+ZM/IaUcvDXVaFf5G5GXity1KmbOf3G9+/LkEzty1nzkCRQTM+pZdgl1hIxBxncc4+okYxWKAuFUvgw0xjvuoh5mEqT9/9QIDAQAB";
Map<Class,Object> keyPairMap=initKeyPair(algorithm,keySize);
PublicKey publicKey=(PublicKey)keyPairMap.get(PublicKey.class);
PrivateKey privateKey=(PrivateKey) keyPairMap.get(PrivateKey.class);
//加密和解密过程
try {
System.out.println("待加密字符串:str="+str);
//将加密结果转化为Base64编码
String result= new String(Base64.encodeBase64(AsymmetricEncryptionUtil.encrypt(publicKey,algorithm,str.getBytes(charset))),charset);
//加密后得Base64字符串
System.out.println("加密后的字节数组转化为 Base64展示="+result);
//将加密的Base64字符串解密-将解密字节数组转Base64字符串
String ostr= new String(AsymmetricEncryptionUtil.decipher(privateKey,algorithm,Base64.decodeBase64(result)),charset);
System.out.println("原字符串="+ostr);
} catch (NoSuchPaddingException e) {
e.printStackTrace();
} catch (InvalidKeyException e) {
e.printStackTrace();
} catch (BadPaddingException e) {
e.printStackTrace();
} catch (IllegalBlockSizeException e) {
e.printStackTrace();
}
//字符串恢复为公私钥对象过程
//私钥恢复为 PrivateKey
PrivateKey priKey=AsymmetricEncryptionUtil.restorePrivateKey(privateKeyBase64,algorithm,charset);
//公钥恢复为 PublicKey
PublicKey pubKey=AsymmetricEncryptionUtil.restorePublicKey(publicKeyBase64,algorithm,charset);
}
/**
* 将 字符串 用指定加密算法 解密
* @param privateKey 私钥
* @param algorithm 算发,如 RSA
* @param strBytes 待解密字节数组
* @return
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
* @throws UnsupportedEncodingException
*/
public static byte[] decipher(PrivateKey privateKey,String algorithm, byte[] strBytes) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
Cipher cipher=Cipher.getInstance(algorithm);
cipher.init(Cipher.DECRYPT_MODE,privateKey);
return cipher.doFinal(strBytes);
}
/**
* 将 字符串 用指定加密算法 加密
* @param publicKey 公钥
* @param algorithm 算法,如 RSA
* @param strBytes 待加密字节数组
* @return
* @throws NoSuchPaddingException
* @throws NoSuchAlgorithmException
* @throws InvalidKeyException
* @throws BadPaddingException
* @throws IllegalBlockSizeException
*/
public static byte[] encrypt(PublicKey publicKey,String algorithm,byte[] strBytes) throws NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
//获取 cipher 对象,指定加密算法 比如 RSA
Cipher cipher = Cipher.getInstance(algorithm);
//初始化 cipher 对象,指定为加密模式,指定公钥
cipher.init(Cipher.ENCRYPT_MODE, publicKey);
return cipher.doFinal(strBytes);
}
/**
* 生成 非对称加密算法 公私钥对的方法-返回默认秘钥格式
* @param algorithm 加密算法
* @param keySize 私钥长度-实际会生成一个近似值
* <li>{@code DiffieHellman} (1024)</li>
* <li>{@code DSA} (1024)</li>
* <li>{@code RSA} (1024, 2048)</li>
* @return
* @throws NoSuchAlgorithmException
*/
public static Map<Class,Object> initKeyPair(String algorithm,int keySize) throws NoSuchAlgorithmException {
//指定算法 RSA、DiffieHellman、DSA
KeyPairGenerator keyPairGenerator=KeyPairGenerator.getInstance(algorithm);
//指定私钥的长度——实际生成的也是近似值
keyPairGenerator.initialize(keySize);
//生成公私钥对
KeyPair kPair=keyPairGenerator.generateKeyPair();
Map<Class,Object> keyPairMap=new HashMap<Class,Object>();
keyPairMap.put(PrivateKey.class,kPair.getPrivate());
keyPairMap.put(PublicKey.class,kPair.getPublic());
return keyPairMap;
}
/**
* 生成 非对称加密算法 公私钥对的方法-返回字符Base64 字符串格式
* @param algorithm 加密算法
* @param keySize 私钥长度-实际会生成一个近似值
* @param charset 字符编码格式,如utf8
* <li>{@code DiffieHellman} (1024)</li>
* <li>{@code DSA} (1024)</li>
* <li>{@code RSA} (1024, 2048)</li>
* @return
* @throws NoSuchAlgorithmException
*/
public static Map<Class,Object> initKeyPairBase64Str(String algorithm,int keySize,String charset) throws NoSuchAlgorithmException, UnsupportedEncodingException {
Map<Class,Object> keyPairMap=initKeyPair(algorithm,keySize);
PrivateKey privateKey=(PrivateKey)keyPairMap.get(PrivateKey.class);
PublicKey publicKey=(PublicKey)keyPairMap.get(PublicKey.class);
//以 Base64 格式输出 私钥,指定字符格式 如 utf8、gbk
String privateKeyStr= new String(Base64.encodeBase64(privateKey.getEncoded()),charset);
//以 Base64 格式输出 公钥,指定字符格式 如 utf8、gbk
String publicKeyStr=new String(Base64.encodeBase64(publicKey.getEncoded()),charset);
System.out.println(privateKey.getEncoded().length);
System.out.println(publicKey.getEncoded().length);
//System.out.println("私钥:"+"algorithm:"+privateKey.getAlgorithm()+";format:"+privateKey.getFormat()+";私钥base64:"+privateKeyStr);
//System.out.println("公钥:"+"algorithm:"+publicKey.getAlgorithm()+";format:"+publicKey.getFormat()+";公钥base64:"+publicKeyStr);
keyPairMap.put(PrivateKey.class,privateKeyStr);
keyPairMap.put(PublicKey.class,publicKeyStr);
return keyPairMap;
}
/**
* 由Base64字符编码恢复 公钥
* @param pubKeyBase64Str 公钥 Base64 编码 字符串
* @param algorithm 算法名称,如 RSA\DSA\DiffieHellman
* @param charset 字符编码格式,如 utf8、gbk
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PublicKey restorePublicKey(String pubKeyBase64Str,String algorithm,String charset) throws NoSuchAlgorithmException, InvalidKeySpecException, UnsupportedEncodingException {
//将Base64 字符串转化为字节数组
byte[] keyBytes=Base64.decodeBase64(pubKeyBase64Str.getBytes(charset));
//公钥标准
X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(keyBytes);
//指定算法 比如 RSA
KeyFactory factory = KeyFactory.getInstance(algorithm);
//获取公钥
PublicKey publicKey = factory.generatePublic(x509EncodedKeySpec);
return publicKey;
}
/**
* 由Base64字符编码恢复 私钥
* @param privateBase64Str 私钥 Base64 编码字符串
* @param algorithm 算法名称,如 RSA\DSA\DiffieHellman
* @param charset 字符编码格式,如 utf8、gbk
* @return
* @throws NoSuchAlgorithmException
* @throws InvalidKeySpecException
*/
public static PrivateKey restorePrivateKey(String privateBase64Str,String algorithm,String charset) throws NoSuchAlgorithmException, InvalidKeySpecException, UnsupportedEncodingException {
//将Base64 字符串转化为字节数组
byte[] keyBytes=Base64.decodeBase64(privateBase64Str.getBytes(charset));
//私钥标准
PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(keyBytes);
//指定算法,比如 RSA
KeyFactory factory = KeyFactory.getInstance(algorithm);
//获取私钥
PrivateKey privateKey = factory.generatePrivate(pkcs8EncodedKeySpec);
return privateKey;
}
}
CloseResourceUtils 关闭IO资源
import java.io.Closeable;
import java.io.IOException;
public class CloseableUtils {
public CloseableUtils() {
}
public static void close(Closeable... args) {
if (args != null && args.length != 0) {
Closeable[] arr$ = args;
int len$ = args.length;
for(int i$ = 0; i$ < len$; ++i$) {
Closeable arg = arr$[i$];
try {
if (arg != null) {
arg.close();
}
} catch (IOException var6) {
System.out.println("CloseableUtils.close exception:", var6);
}
}
}
}
}
BrowserInfoUtils 浏览器信息
import javax.servlet.http.HttpServletRequest;
public class BrowserInfoUtils {
/**
* 获取来访者的浏览器版本
* @param request
* @return
*/
public static String getRequestBrowserInfo(HttpServletRequest request){
String browserVersion = null;
String header = request.getHeader("user-agent");
if(header == null || header.equals("")){
return "";
}
if(header.indexOf("MSIE")>0){
browserVersion = "IE";
}else if(header.indexOf("Firefox")>0){
browserVersion = "Firefox";
}else if(header.indexOf("Chrome")>0){
browserVersion = "Chrome";
}else if(header.indexOf("Safari")>0){
browserVersion = "Safari";
}else if(header.indexOf("Camino")>0){
browserVersion = "Camino";
}else if(header.indexOf("Konqueror")>0){
browserVersion = "Konqueror";
}
return browserVersion;
}
}
HttpURLConnectionUtils
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
/**
* @Title:
* @Description:
* @Copyright: Copyright(c)2018
* @Author: jie.wu
* @Date:2018-09-12 18:18
*/
public class HttpURLConnectionUtils {
/**
* POST 方式发起 httpclient 请求
* @param remoteUrl
* @param xmlStr
* @param encoding
* @return
*/
public static String HttpURLConnectionPost(String remoteUrl, String xmlStr, String encoding){
return sendHttpURLConnection(remoteUrl,xmlStr, encoding,"POST");
}
/**
* httpclient 发送基本方法
* 可以发送xml,json,a=1&b=2&c= 等格式的字符串
*
* @param remoteUrl
* @param xmlStr
* @param encoding ytf8\GBK
* @param requestMethod GET\POST
*
* @return
*/
public static String sendHttpURLConnection(String remoteUrl, String xmlStr, String encoding,String requestMethod) {
String strResponse = "";
String strMessage = "";
InputStream inputStream = null;
OutputStream outputStream = null;
BufferedReader reader = null;
OutputStreamWriter writer = null;
System.out.println("requestXml="+xmlStr);
//logger.info("requestXml={}",xmlStr);
URL url;
HttpURLConnection connection;
try {
url = new URL(remoteUrl);
connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.setDoOutput(true);
//connection.setRequestMethod(requestMethod);
connection.setRequestMethod("POST");
connection.setAllowUserInteraction(true);
// 设置超时
String strTimeOut = "6000";
if (strTimeOut != null) {
connection.setConnectTimeout(Integer.parseInt(strTimeOut));
connection.setReadTimeout(Integer.parseInt(strTimeOut));
}
connection.connect();
outputStream = connection.getOutputStream();
writer = new OutputStreamWriter(outputStream, encoding);
writer.write(xmlStr);
writer.flush();
inputStream = connection.getInputStream();
int status = connection.getResponseCode();
if (status == 200) {
reader = new BufferedReader(new InputStreamReader(inputStream, encoding));
while ((strMessage = reader.readLine()) != null) {
strResponse += strMessage;
}
} else {
strResponse = "error http's status=" + status;
}
} catch (MalformedURLException e) {
} catch (IOException e) {
} catch (Exception e) {
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
if (reader != null) {
reader.close();
}
if (outputStream != null) {
outputStream.close();
}
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
System.out.println("responseXml="+strResponse);
//logger.info("responseXml={}",strResponse);
return strResponse;
}
}
IPAddrUtils 获取ip地址+ip解析为地址
maven 依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.4</version>
<!-- 必须加jdk的版本号 -->
<classifier>jdk15</classifier>
</dependency>
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import net.sf.json.JSONObject;
public class IPAddrUtils {
/**
* 获取 IP 信息
* @param request
* @return
*/
public static String getIpAddr(HttpServletRequest request) {
//获取所有的代理IP
String ipAddress = request.getHeader("x-forwarded-for");
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("Proxy-Client-IP");
}
if (ipAddress == null || ipAddress.length() == 0|| "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("WL-Proxy-Client-IP");
}
//获取用户的真实IP
if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getHeader("X-Real-Ip");
}
if (ipAddress == null || ipAddress.length() == 0|| "unknown".equalsIgnoreCase(ipAddress)) {
ipAddress = request.getRemoteAddr();
if (ipAddress.equals("127.0.0.1")) {
// 根据网卡取本机配置的IP
InetAddress inet = null;
try {
inet = InetAddress.getLocalHost();
ipAddress = inet.getHostAddress();
} catch (UnknownHostException e) {
System.out.println("出现异常:"+e.toString());
}
}
}
// 对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
// "***.***.***.***".length() = 15
if (ipAddress != null && ipAddress.length() > 15) {
if (ipAddress.indexOf(",") > 0) {
ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
}
}
if("0:0:0:0:0:0:0:1".equals(ipAddress)){
ipAddress="127.0.0.1";
}
return ipAddress;
}
//访问这个地址获取 ip 所属到地区信息
private final static String remoteUrl="http://ip.taobao.com/service/getIpInfo.php?ip=";
private final static String encoding="utf-8";
/**
* 根据 ip 查询地址信息
* @param ip
* @return
*/
public static JSONObject getAreaInfoJsonObjectByIp(String ip){
ip="223.223.193.194";
String xmlStr="";
String result=HttpURLConnectionUtils.HttpURLConnectionPost(remoteUrl+ip, xmlStr, encoding);
if(StringUtils.isNotBlank(result)){
JSONObject json=JSONObject.fromObject(result);
int code=(int)json.get("code");
if(0==code){
JSONObject innerJson=(JSONObject)json.get("data");
System.out.println("ip对应的地区为:"+(String)innerJson.get("country")+innerJson.get("region")+innerJson.getString("city"));
}
return json;
}else{
return null;
}
}
/**
* 根据ip 获取组装好的地址
* @param ip
* @return
*/
public static String getAreaInfoStringByIp(String ip){
JSONObject json=getAreaInfoJsonObjectByIp(ip);
if(json!=null){
int code=(Integer)json.get("code");
if(0==code){
JSONObject innerJson=(JSONObject)json.get("data");
StringBuilder stringBuilder=new StringBuilder();
stringBuilder.append(innerJson.get("country")).append(innerJson.get("region")).append(innerJson.getString("city"));
return stringBuilder.toString();
}
}else{
return "未知区域";
}
return "未知区域";
}
}
SystemInfoUtils 操作系统信息
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.servlet.http.HttpServletRequest;
public class SystemInfoUtils {
private final static Pattern pattern = Pattern.compile(";\\s?[^;\\s]*?(\\s?\\S*?)\\s?(Build)?/");
/**
* 获取系统版本信息
* @param request
* @return
*/
public static String getRequestSystemInfo(HttpServletRequest request){
String systenInfo = null;
String userAgent = request.getHeader("USER-AGENT");
if(userAgent == null || userAgent.equals("")){
return "";
}
System.out.println("userAgent="+userAgent);
boolean isMobile= checkFromMobile(userAgent.toLowerCase());
if(isMobile) {
if(userAgent.indexOf("iPhone") != -1){
return "iPhone";
}
if(userAgent.indexOf("iPad") != -1){
return "iPad";
}
if(userAgent.indexOf("NOKIA") != -1 || userAgent.indexOf("Nokia")!=-1){
return "NOKIA";
}
if(userAgent.indexOf("Windows Phone") != -1){
return "Windows Phone";
}
if(userAgent.indexOf("Nexus") != -1){
return "Nexus";
}
Matcher matcher = pattern.matcher(userAgent);
if (matcher.find()) {
systenInfo = matcher.group(1).trim();
}
}else{
//得到用户的操作系统 https://blog.csdn.net/flyingpig2016/article/details/53282895
if (userAgent.indexOf("NT 6.0") > 0){
systenInfo = "Windows Vista/Server 2008";
} else if (userAgent.indexOf("NT 5.1") > 0){
systenInfo = "Windows XP";
} else if (userAgent.indexOf("NT 6.0") > 0){
systenInfo = "Windows Vista";
} else if (userAgent.indexOf("NT 6.1") > 0){
systenInfo = "Windows 7";
}else if (userAgent.indexOf("NT 6.2") > 0){
systenInfo = "Windows 8";
}else if (userAgent.indexOf("NT 6.3") > 0){
systenInfo = "Windows 9";
} else if (userAgent.indexOf("NT6.4") > 0||userAgent.indexOf("10.0") > 0){
systenInfo = "Windows 10";
}else if (userAgent.indexOf("NT 5") > 0){
systenInfo = "Windows 2000";
} else if (userAgent.indexOf("Mac") > 0){
systenInfo = "Mac";
} else if (userAgent.indexOf("Unix") > 0){
systenInfo = "UNIX";
} else if (userAgent.indexOf("Linux") > 0){
systenInfo = "Linux";
} else if (userAgent.indexOf("SunOS") > 0){
systenInfo = "SunOS";
}else{
systenInfo = "其他";
}
}
return systenInfo;
}
private static String phoneReg = "\\b(ip(hone|od)|android|opera m(ob|in)i"
+"|windows (phone|ce)|blackberry"
+"|s(ymbian|eries60|amsung)|p(laybook|alm|rofile/midp"
+"|laystation portable)|nokia|fennec|htc[-_]"
+"|mobile|up.browser|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
private static String tableReg = "\\b(ipad|tablet|(Nexus 7)|up.browser"
+"|[1-4][0-9]{2}x[1-4][0-9]{2})\\b";
private static Pattern phonePat = Pattern.compile(phoneReg, Pattern.CASE_INSENSITIVE);
private static Pattern tablePat = Pattern.compile(tableReg, Pattern.CASE_INSENSITIVE);
/**
* 如果是手机端则返回 true
* @param userAgent
* @return
*/
private static boolean checkFromMobile(String userAgent){
if(null == userAgent){
userAgent = "";
}
Matcher matcherPhone = phonePat.matcher(userAgent);
Matcher matcherTable = tablePat.matcher(userAgent);
if(matcherPhone.find() || matcherTable.find()){
return true;
} else {
return false;
}
}
}
生成8位随机密码
0-26+97=97-123 对应 ASCII码中 0-9,a-z,A-Z
/**
* 生成随机密码的工具类
*/
public class RandomPasswordUtils {
/**
* 生成8位随机数字、大小写字母
* @return
*/
public static String getRandomPassword() {
String result = "";
for (int i = 0; i<8; i++){
int intVal = (int)(Math.random()*26+97);
result = result +(char) intVal;
}
return result;
}
}
音频文件格式在线转化
https://app.xunjiepdf.com/mp32ogg/
在线工具箱
https://www.matools.com/#
自动替换字符串工具类
Maven 依赖
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.7</version>
</dependency>
- 先来看一个简单的例子——能替换就替换,否则不替换
@Test
public void test1(){
//设定被替换规则 map ,这里只设定 testvalue 这个值
Map valuesMap = new HashMap();
valuesMap.put("testvalue","111");
String beginString = "The ${animal} jumped over the ${target}. ${testvalue}";
StrSubstitutor sub = new StrSubstitutor(valuesMap,"${","}");
String result=sub.replace(beginString,valuesMap);
System.out.println(result);
}
输出:因为只设定了testvalue,所以${animal} 和 ${target} 未被替换
The ${animal} jumped over the ${target}. 111
- 改进版——如果没有具体替换规则,则替换为空默认字符串——比如 default
@Test
public void test2() {
Map valuesMap = new HashMap();
valuesMap.put("testvalue", "111");
String beginString = "The ${animal} jumped over the ${target}. ${testvalue}";
StrSubstitutor sub = new StrSubstitutor(valuesMap, "${", "}");
//获取所有需被替换的字符
List<String> strList = getVarsFromStr(beginString, "\\$\\{", "}", "${");
//获取map中不包含的字符
strList.forEach(item -> {
if (!valuesMap.keySet().contains(item)) {
valuesMap.put(item, "default");
}
});
String result = sub.replace(beginString, valuesMap);
System.out.println(result);
}
private List<String> getVarsFromStr(String str, String startStr, String endStr, String startWith) {
if (StringUtils.isBlank(str) || !str.contains(startWith)) {
return com.google.common.collect.Lists.newArrayList();
}
String strLocal = str.substring(str.indexOf(startWith));
String[] split = strLocal.split(startStr);
if (split.length == 0) {
return com.google.common.collect.Lists.newArrayList();
}
List<String> list = com.google.common.collect.Lists.newArrayList();
for (String item : split) {
int index = item.indexOf(endStr);
if (index >= 1) {
list.add(item.substring(0, index));
}
}
return list;
}