init:删除无用配置

This commit is contained in:
zhangzq
2025-06-25 09:33:37 +08:00
parent 303b7a08c9
commit 30cc7f94fb
89 changed files with 1429 additions and 3012 deletions

View File

@@ -20,8 +20,7 @@ import lombok.Getter;
import lombok.Setter;
import org.nl.common.base.BaseDTO;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
//import javax.validation.constraints.NotBlank;
import java.io.Serializable;
import java.util.List;
@@ -41,29 +40,25 @@ public class DeptVo extends BaseDTO implements Serializable {
private String ext_id;
private Integer dept_sort;
@NotBlank
private String name;
private String zh_name;
private String en_name;
private String in_name;
@NotNull
private Boolean is_used;
private Long pid;
private Integer sub_count = 0;
/**

View File

@@ -19,7 +19,6 @@ package org.nl.common.domain.vo;
import lombok.Getter;
import lombok.Setter;
import javax.validation.constraints.NotBlank;
import java.io.Serializable;
/**
@@ -33,20 +32,18 @@ public class RoleVo implements Serializable {
private Long role_id;
@NotBlank
private String name;
private Integer level = 3;
private String remark;
private String order_seq;
private String is_used;
}

View File

@@ -13,33 +13,26 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.nl.common.domain.aspect;
package org.nl.common.logging.aspect;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import io.netty.util.internal.ThrowableUtil;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.nl.common.utils.RequestHolder;
import org.nl.common.utils.SecurityUtils;
import org.nl.common.utils.StringUtils;
import org.nl.common.utils.ThrowableUtil;
import org.nl.system.service.logging.ISysLogService;
import org.nl.system.service.logging.dao.SysLog;
import org.nl.common.utils.*;
import org.nl.config.lucene.LuceneAppender;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
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 java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
@@ -47,67 +40,63 @@ import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author Zheng Jie
* @date 2018-11-24
*/
@Component
@Aspect
@Slf4j
public class LogAspect {
private final ISysLogService logService;
ThreadLocal<Long> currentTime = new ThreadLocal<>();
public LogAspect(ISysLogService logService) {
this.logService = logService;
}
/**
* 配置切入点
*/
@Pointcut("@annotation(org.nl.common.logging.annotation.Log)")
public void logPointcut() {
// 该方法无方法体,主要为了让同类中其他方法使用此切入点
}
/**
* 配置环绕通知,使用在方法logPointcut()上注册的切入点
*
* @param joinPoint join point for advice
*/
@Around("logPointcut()")
public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
HttpServletResponse response = attributes.getResponse();
@Around("@annotation(logInfo)")
public Object logAround(ProceedingJoinPoint joinPoint,org.nl.common.logging.annotation.Log logInfo) throws Throwable {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
// 方法路径
String methodName = joinPoint.getTarget().getClass().getName() + "." + signature.getName() + "()";
String params = getParameter(method, joinPoint.getArgs());
HttpServletRequest request = RequestHolder.getHttpServletRequest();
String url = request.getRequestURI();
String requestIp = IPUtil.getIp(request);
MDC.put("requestMethod",url);
MDC.put("requestIp", requestIp);
MDC.put("requestTime", DateUtil.now());
Object result = null;
long comming = System.currentTimeMillis();
try {
log.info("[--request--][请求接口:{}][请求参数:{}]",url,params);
result = joinPoint.proceed();
}catch (Exception ex){
Object result;
currentTime.set(System.currentTimeMillis());
result = joinPoint.proceed();
SysLog log = new SysLog("INFO", System.currentTimeMillis() - currentTime.get());
currentTime.remove();
logService.save(getUsername(), StringUtils.getBrowser(request), StringUtils.getIp(request), joinPoint, log);
StringBuffer errorStack = new StringBuffer();
errorStack.append("<br/>【异常堆栈:");
String errorMsg = ex.getMessage();
int x = 0;
StackTraceElement[] stackTrace = ex.getStackTrace();
if (stackTrace!=null && stackTrace.length>0){
for (StackTraceElement stack : stackTrace) {
x++;errorStack.append(stack.toString().replaceAll("<",">")).append("<br/>");
if (x>10){ break; }
}
}
log.error("[-requestError-][请求接口:{}]【异常信息:{}】[请求参数:{}] {}", url,errorMsg,params, errorStack.append("").toString());
throw ex;
}finally {
log.info("[--response--][请求接口:{} 执行结束][耗时:{}s]",url,(System.currentTimeMillis() - comming)/1000);
MDC.clear();
}
return result;
}
/**
* 根据方法和传入的参数获取请求参数
*/
private String getParameter(Method method, Object[] args) {
List<Object> argList = new ArrayList<>();
Parameter[] parameters = method.getParameters();
@@ -132,24 +121,7 @@ public class LogAspect {
if (argList.size() == 0) {
return "";
}
return argList.size() == 1 ? JSONUtil.toJsonStr(argList.get(0)) : JSONUtil.toJsonStr(argList);
}
/**
* 配置异常通知
*
* @param joinPoint join point for advice
* @param e exception
*/
@AfterThrowing(pointcut = "logPointcut()", throwing = "e")
public void logAfterThrowing(JoinPoint joinPoint, Throwable e) {
SysLog log = new SysLog("ERROR", System.currentTimeMillis() - currentTime.get());
currentTime.remove();
log.setException_detail(ThrowableUtil.getStackTrace(e).getBytes());
HttpServletRequest request = RequestHolder.getHttpServletRequest();
logService.save(getUsername(), StringUtils.getBrowser(request), StringUtils.getIp(request), (ProceedingJoinPoint) joinPoint, log);
return JSON.toJSONString(argList);
}
public String getUsername() {

View File

@@ -1,103 +0,0 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.nl.common.mnt.util;
import cn.hutool.core.io.IoUtil;
import com.jcraft.jsch.ChannelShell;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import lombok.extern.slf4j.Slf4j;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.util.Vector;
/**
* 执行shell命令
*
* @author: ZhangHouYing
* @date: 2019/8/10
*/
@Slf4j
public class ExecuteShellUtil {
private Vector<String> stdout;
Session session;
public ExecuteShellUtil(final String ipAddress, final String username, final String password,int port) {
try {
JSch jsch = new JSch();
session = jsch.getSession(username, ipAddress, port);
session.setPassword(password);
session.setConfig("StrictHostKeyChecking", "no");
session.connect(3000);
} catch (Exception e) {
log.error(e.getMessage(),e);
}
}
public int execute(final String command) {
int returnCode = 0;
ChannelShell channel = null;
PrintWriter printWriter = null;
BufferedReader input = null;
stdout = new Vector<String>();
try {
channel = (ChannelShell) session.openChannel("shell");
channel.connect();
input = new BufferedReader(new InputStreamReader(channel.getInputStream()));
printWriter = new PrintWriter(channel.getOutputStream());
printWriter.println(command);
printWriter.println("exit");
printWriter.flush();
log.info("The remote command is: ");
String line;
while ((line = input.readLine()) != null) {
stdout.add(line);
System.out.println(line);
}
} catch (Exception e) {
log.error(e.getMessage(),e);
return -1;
}finally {
IoUtil.close(printWriter);
IoUtil.close(input);
if (channel != null) {
channel.disconnect();
}
}
return returnCode;
}
public void close(){
if (session != null) {
session.disconnect();
}
}
public String executeForResult(String command) {
execute(command);
StringBuilder sb = new StringBuilder();
for (String str : stdout) {
sb.append(str);
}
return sb.toString();
}
}

View File

@@ -1,37 +0,0 @@
/*
* Copyright 2019-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.nl.common.security.config;
import org.nl.common.security.config.bean.LoginProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* @apiNote 配置文件转换Pojo类的 统一配置 类
* @author: liaojinlong
* @date: 2020/6/10 19:04
*/
@Configuration
public class ConfigBeanConfiguration {
@Bean
@ConfigurationProperties(prefix = "login", ignoreUnknownFields = true)
public LoginProperties loginProperties() {
return new LoginProperties();
}
}

View File

@@ -1,61 +0,0 @@
/*
* Copyright 2019-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.nl.common.security.config.bean;
import lombok.Data;
/**
* 登录验证码配置信息
*
* @author: liaojinlong
* @date: 2020/6/10 18:53
*/
@Data
public class LoginCode {
/**
* 验证码配置
*/
private LoginCodeEnum codeType;
/**
* 验证码有效期 分钟
*/
private Long expiration = 2L;
/**
* 验证码内容长度
*/
private int length = 2;
/**
* 验证码宽度
*/
private int width = 111;
/**
* 验证码高度
*/
private int height = 36;
/**
* 验证码字体
*/
private String fontName;
/**
* 字体大小
*/
private int fontSize = 25;
public LoginCodeEnum getCodeType() {
return codeType;
}
}

View File

@@ -1,43 +0,0 @@
/*
* Copyright 2019-2020 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.nl.common.security.config.bean;
/**
* 验证码配置枚举
*
* @author: liaojinlong
* @date: 2020/6/10 17:40
*/
public enum LoginCodeEnum {
/**
* 算数
*/
arithmetic,
/**
* 中文
*/
chinese,
/**
* 中文闪图
*/
chinese_gif,
/**
* 闪图
*/
gif,
spec
}

View File

@@ -1,112 +0,0 @@
/*
* Copyright 2019-2020 the original author or authors.
*
* Licensed under the Apache License, Version loginCode.length.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-loginCode.length.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.nl.common.security.config.bean;
import cn.hutool.core.util.StrUtil;
import com.wf.captcha.*;
import com.wf.captcha.base.Captcha;
import lombok.Data;
import org.nl.common.exception.BadConfigurationException;
import org.nl.config.language.LangProcess;
import java.awt.*;
import java.util.Objects;
/**
* 配置文件读取
*
* @author liaojinlong
* @date loginCode.length0loginCode.length0/6/10 17:loginCode.length6
*/
@Data
public class LoginProperties {
/**
* 账号单用户 登录
*/
private boolean singleLogin = false;
private LoginCode loginCode;
/**
* 用户登录信息缓存
*/
private boolean cacheEnable;
public boolean isSingleLogin() {
return singleLogin;
}
public boolean isCacheEnable() {
return cacheEnable;
}
/**
* 获取验证码生产类
*
* @return /
*/
public Captcha getCaptcha() {
if (Objects.isNull(loginCode)) {
loginCode = new LoginCode();
if (Objects.isNull(loginCode.getCodeType())) {
loginCode.setCodeType(LoginCodeEnum.arithmetic);
}
}
return switchCaptcha(loginCode);
}
/**
* 依据配置信息生产验证码
*
* @param loginCode 验证码配置信息
* @return /
*/
private Captcha switchCaptcha(LoginCode loginCode) {
Captcha captcha;
synchronized (this) {
switch (loginCode.getCodeType()) {
case arithmetic:
// 算术类型 https://gitee.com/whvse/EasyCaptcha
captcha = new ArithmeticCaptcha(loginCode.getWidth(), loginCode.getHeight());
// 几位数运算,默认是两位
captcha.setLen(loginCode.getLength());
break;
case chinese:
captcha = new ChineseCaptcha(loginCode.getWidth(), loginCode.getHeight());
captcha.setLen(loginCode.getLength());
break;
case chinese_gif:
captcha = new ChineseGifCaptcha(loginCode.getWidth(), loginCode.getHeight());
captcha.setLen(loginCode.getLength());
break;
case gif:
captcha = new GifCaptcha(loginCode.getWidth(), loginCode.getHeight());
captcha.setLen(loginCode.getLength());
break;
case spec:
captcha = new SpecCaptcha(loginCode.getWidth(), loginCode.getHeight());
captcha.setLen(loginCode.getLength());
break;
default:
throw new BadConfigurationException(LangProcess.msg("login_codeError"));
}
}
if(StrUtil.isNotEmpty(loginCode.getFontName())){
captcha.setFont(new Font(loginCode.getFontName(), Font.PLAIN, loginCode.getFontSize()));
}
return captcha;
}
}

View File

@@ -1,21 +0,0 @@
package org.nl.common.security.satoken;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
/**
* @author: lyd
* @description: redis监听配置
* @Date: 2022/10/8
*/
@Configuration
public class RedisListenerConfig {
@Bean
RedisMessageListenerContainer container(RedisConnectionFactory connectionFactory) {
RedisMessageListenerContainer container = new RedisMessageListenerContainer();
container.setConnectionFactory(connectionFactory);
return container;
}
}

View File

@@ -1,54 +0,0 @@
package org.nl.common.security.satoken;
import cn.dev33.satoken.interceptor.SaInterceptor;
import cn.dev33.satoken.jwt.StpLogicJwtForSimple;
import cn.dev33.satoken.stp.StpLogic;
import cn.dev33.satoken.stp.StpUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* @author: lyd
* @description: sa-token的配置路由拦截
* @Date: 2022-09-20
*/
@Slf4j
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {
/**
* 白名单
*/
@Autowired
private SecurityProperties securityProperties;
/**
* Sa-Token 整合 jwt (Simple 简单模式)
* @return StpLogic/
*/
@Bean
public StpLogic getStpLogicJwt() {
return new StpLogicJwtForSimple();
}
/**
* 注册 Sa-Token 拦截器,打开注解式鉴权功能
* @param registry
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
/*
* 注册 Sa-Token 拦截器,打开注解式鉴权功能
* .excludePathPatterns(securityProperties.getExcludes()): 白名单
*/
registry.addInterceptor(new SaInterceptor(handle -> StpUtil.checkLogin()))
.addPathPatterns("/**")
.excludePathPatterns(securityProperties.getExcludes());
}
}

View File

@@ -1,20 +0,0 @@
package org.nl.common.security.satoken;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* @author: lyd
* @description: 白名单 - 统一放到yml管理
* @Date: 2022/9/22
*/
@Data
@Component
@ConfigurationProperties(prefix = "security")
public class SecurityProperties {
/**
* 排除路径
*/
private String[] excludes;
}

View File

@@ -1,38 +0,0 @@
package org.nl.common.security.satoken;
import cn.dev33.satoken.stp.StpInterface;
import org.nl.common.utils.SecurityUtils;
import org.springframework.stereotype.Component;
import java.util.List;
/**
* @author: lyd
* @description: stp接口impl 自定义权限验证接口扩展 保证此类被springboot扫描即可完成sa-token的自定义权限验证扩展
* @Date: 2022-09-20
*/
@Component
public class StpInterfaceImpl implements StpInterface {
/**
* 用户权限获取
* @param o login存入的值此处存放用户id
* @param s
* @return
*/
@Override
public List<String> getPermissionList(Object o, String s) {
return SecurityUtils.getCurrentUserPermissions();
}
/**
* 角色权限获取 - 数据库没有设计角色code因此不推荐使用角色鉴权
* @param o
* @param s
* @return
*/
@Override
public List<String> getRoleList(Object o, String s) {
return null;
}
}

View File

@@ -1,88 +0,0 @@
## 关于satoken的提示
### 本系统采用两个session存放相关信息
1、其中tokenSession存放的是
提供公共模块使用获取是Object可以直接强转此实体.
主要使用在 SecurityUtils类上使用的key: userInfo
```java
@Data
public class CurrentUser implements Serializable {
@JsonSerialize(using = ToStringSerializer.class)
private String id;
private String username;
private Object user;
private List<String> permissions = new ArrayList<>();
}
```
2、Session存放的是UserDto,提供业务模块使用使用的key: UserDto
```java
@Getter
@Setter
public class UserDto extends BaseDTO implements Serializable {
@JsonSerialize(using = ToStringSerializer.class)
private String id;
private Set<RoleSmallDto> roles;
private Set<JobSmallDto> jobs;
private DeptSmallDto dept;
private Long deptId;
private String username;
private String nickName;
private String email;
private String phone;
private String gender;
private String avatarName;
private String avatarPath;
private String extId;
private String extuserId;
@JsonIgnore
private String password;
private Boolean enabled;
@JsonIgnore
private Boolean isAdmin = false;
private Date pwdResetTime;
}
```
### 加密规则
```
SaSecureUtil.md5BySalt("123456", "salt")
```
### 另一种拦截
```
registry.addInterceptor(new SaRouteInterceptor((request, response, handler) -> {
System.out.println(SaHolder.getRequest().getRequestPath());
// 登录验证 -- 排除多个路径
SaRouter
// 获取所有的
.match("/**")
// 排除下不需要拦截的
.notMatch(securityProperties.getExcludes())
// 对未排除的路径进行检查
.check(() -> {
// 检查是否登录 是否有token
StpUtil.checkLogin();
});
})).addPathPatterns("/**");
registry.addInterceptor(new SaAnnotationInterceptor()).addPathPatterns("/**");
```

View File

@@ -1,49 +0,0 @@
package org.nl.common.security.service;///*
// * Copyright 2019-2020 the original author or authors.
// *
// * Licensed under the Apache License, Version 2.0 (the "License");
// * you may not use this file except in compliance with the License.
// * You may obtain a copy of the License at
// *
// * http://www.apache.org/licenses/LICENSE-2.0
// *
// * Unless required by applicable law or agreed to in writing, software
// * distributed under the License is distributed on an "AS IS" BASIS,
// * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// * See the License for the specific language governing permissions and
// * limitations under the License.
// */
//
//package org.nl.common.security.service;
//
//import cn.hutool.core.util.StrUtil;
//import org.springframework.stereotype.Component;
//
///**
// * @author: liaojinlong
// * @date: 2020/6/11 18:01
// * @apiNote: 用于清理 用户登录信息缓存为防止Spring循环依赖与安全考虑 ,单独构成工具类
// */
//@Component
//public class UserCacheClean {
//
// /**
// * 清理特定用户缓存信息<br>
// * 用户信息变更时
// *
// * @param userName /
// */
// public void cleanUserCache(String userName) {
// if (StrUtil.isNotEmpty(userName)) {
//// UserDetailsServiceImpl.userDtoCache.remove(userName);
// }
// }
//
// /**
// * 清理所有用户的缓存信息<br>
// * ,如发生角色授权信息变化,可以简便的全部失效缓存
// */
//// public void cleanAll() {
//// UserDetailsServiceImpl.userDtoCache.clear();
//// }
//}

View File

@@ -0,0 +1,97 @@
/*
* Copyright 2019-2020 Zheng Jie
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.nl.common.utils;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
/**
* @author Zheng Jie
* 字符串工具类, 继承org.apache.commons.lang3.StringUtils类
*/
@Slf4j
public class IPUtil {
public static String IP = null;
/**
* 获取当前机器的IP
*
* @return /
*/
public static String getLocalIp() {
if (IP!=null){
return IP;
}
try {
InetAddress candidateAddress = null;
// 遍历所有的网络接口
for (Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces(); interfaces.hasMoreElements();) {
NetworkInterface anInterface = interfaces.nextElement();
// 在所有的接口下再遍历IP
for (Enumeration<InetAddress> inetAddresses = anInterface.getInetAddresses(); inetAddresses.hasMoreElements();) {
InetAddress inetAddr = inetAddresses.nextElement();
// 排除loopback类型地址
if (!inetAddr.isLoopbackAddress()) {
if (inetAddr.isSiteLocalAddress()) {
// 如果是site-local地址就是它了
return inetAddr.getHostAddress();
} else if (candidateAddress == null) {
// site-local类型的地址未被发现先记录候选地址
candidateAddress = inetAddr;
}
}
}
}
if (candidateAddress != null) {
return candidateAddress.getHostAddress();
}
// 如果没有发现 non-loopback地址.只能用最次选的方案
InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
if (jdkSuppliedAddress == null) {
return "";
}
IP = jdkSuppliedAddress.getHostAddress();
return jdkSuppliedAddress.getHostAddress();
} catch (Exception e) {
return "";
}
}
public static String getIp(HttpServletRequest request) {
String ip = request.getHeader("X-Forwarded-For");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
if (ip != null && ip.contains(",")) {
String[] ipArray = ip.split(",");
ip = ipArray[0];
}
return ip;
}
}

View File

@@ -1,6 +1,7 @@
package org.nl.common.utils;
import org.apache.commons.codec.binary.Base64;
import org.nl.common.exception.BadRequestException;
import javax.crypto.Cipher;
import java.security.*;
@@ -18,6 +19,8 @@ public class RsaUtils {
private static final String SRC = "123456";
public static final String KEY = "MIIBUwIBADANBgkqhkiG9w0BAQEFAASCAT0wggE5AgEAAkEA0vfvyTdGJkdbHkB8mp0f3FE0GYP3AYPaJF7jUd1M0XxFSE2ceK3k2kw20YvQ09NJKk+OMjWQl9WitG9pB6tSCQIDAQABAkA2SimBrWC2/wvauBuYqjCFwLvYiRYqZKThUS3MZlebXJiLB+Ue/gUifAAKIg1avttUZsHBHrop4qfJCwAI0+YRAiEA+W3NK/RaXtnRqmoUUkb59zsZUBLpvZgQPfj1MhyHDz0CIQDYhsAhPJ3mgS64NbUZmGWuuNKp5coY2GIj/zYDMJp6vQIgUueLFXv/eZ1ekgz2Oi67MNCk5jeTF2BurZqNLR3MSmUCIFT3Q6uHMtsB9Eha4u7hS31tj1UWE+D+ADzp59MGnoftAiBeHT7gDMuqeJHPL4b+kC+gzV4FGTfhR9q3tTbklZkD2A==";
public static void main(String[] args) throws Exception {
System.out.println("\n");
RsaKeyPair keyPair = generateKeyPair();
@@ -111,14 +114,18 @@ public class RsaUtils {
* @return /
* @throws Exception /
*/
public static String decryptByPrivateKey(String privateKeyText, String text) throws Exception {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyText));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] result = cipher.doFinal(Base64.decodeBase64(text));
return new String(result);
public static String decryptByPrivateKey(String privateKeyText, String text) {
try {
PKCS8EncodedKeySpec pkcs8EncodedKeySpec5 = new PKCS8EncodedKeySpec(Base64.decodeBase64(privateKeyText));
KeyFactory keyFactory = KeyFactory.getInstance("RSA");
PrivateKey privateKey = keyFactory.generatePrivate(pkcs8EncodedKeySpec5);
Cipher cipher = Cipher.getInstance("RSA");
cipher.init(Cipher.DECRYPT_MODE, privateKey);
byte[] result = cipher.doFinal(Base64.decodeBase64(text));
return new String(result);
}catch (Exception ex){
throw new BadRequestException(ex.getMessage());
}
}
/**

View File

@@ -19,8 +19,6 @@ import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.ip2region.core.Ip2regionSearcher;
import net.dreamlu.mica.ip2region.core.IpInfo;
import org.nl.config.ElAdminProperties;
import org.nl.config.SpringContextHolder;
@@ -42,10 +40,6 @@ public class StringUtils {
private static final char SEPARATOR = '_';
private static final String UNKNOWN = "unknown";
/**
* 注入bean
*/
private final static Ip2regionSearcher IP_SEARCHER = SpringContextHolder.getBean(Ip2regionSearcher.class);
/**
@@ -192,14 +186,6 @@ public class StringUtils {
/**
* 根据ip获取详细地址
*/
public static String getLocalCityInfo(String ip) {
IpInfo ipInfo = IP_SEARCHER.memorySearch(ip);
if(ipInfo != null){
return ipInfo.getAddress();
}
return null;
}
//浏览器信息
public static String getBrowser(HttpServletRequest request) {
return "";

View File

@@ -16,7 +16,6 @@
package org.nl.common.utils;
import cn.hutool.core.util.ObjectUtil;
import org.hibernate.validator.internal.constraintvalidators.hv.EmailValidator;
import org.nl.common.exception.BadRequestException;
import org.nl.config.language.LangProcess;
@@ -40,6 +39,6 @@ public class ValidationUtil{
* 验证是否为邮箱
*/
public static boolean isEmail(String email) {
return new EmailValidator().isValid(email, null);
return true;
}
}