package com.vci.ubcs.starter.web.util;
|
|
//package com.vci.web.util;
|
|
import com.alibaba.fastjson.JSONObject;
|
import com.alibaba.fastjson.serializer.SerializerFeature;
|
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
|
import com.vci.ubcs.starter.exception.VciBaseException;
|
import com.vci.ubcs.starter.web.pagemodel.SessionInfo;
|
import org.slf4j.Logger;
|
import org.slf4j.LoggerFactory;
|
import org.springframework.stereotype.Component;
|
|
import javax.servlet.http.HttpServletRequest;
|
import java.beans.IntrospectionException;
|
import java.beans.PropertyDescriptor;
|
import java.lang.reflect.*;
|
import java.math.BigDecimal;
|
import java.net.InetAddress;
|
import java.net.NetworkInterface;
|
import java.util.*;
|
import java.util.stream.Collectors;
|
|
/**
|
* 通用工具类
|
* @author weidy
|
* @date 2021-2-13
|
*/
|
@Component
|
public class WebUtil extends VciBaseUtil {
|
|
/**
|
* 全部标记,常用语树形展示时
|
*/
|
public static final String ALL = "${all}";
|
|
/**
|
* 是否持久化
|
*/
|
private static ThreadLocal<String> needPersistenceInThread = new ThreadLocal<>();
|
/**
|
* 日志对象
|
*/
|
private static Logger logger = LoggerFactory.getLogger(WebUtil.class);
|
|
/**
|
* json字符串转为对象
|
* @param jsonString json的字符串
|
* @param beanClass bean的类
|
* @return bean
|
*/
|
public static <T> T jsonString2JavaBean(String jsonString,Class<T> beanClass){
|
return (T)JSONObject.parseObject(jsonString, beanClass);
|
}
|
|
/**
|
* 从json字符串中获取第一个对象
|
* @param jsonString json的字符串
|
* @param beanClass Bean的类
|
* @return 从列表里获取第一个对象
|
*/
|
public static <T> T getFirstObjectFromJson(String jsonString,Class<T> beanClass){
|
if(!isNull(jsonString)) {
|
return JSONObject.parseArray(jsonString, beanClass).get(0);
|
} else {
|
return null;
|
}
|
}
|
|
/**
|
* 获取sessionInfo对象
|
* @return 获取当前用户的信息
|
*/
|
public static SessionInfo getSessionInfo(){
|
try{
|
return getCurrentUserSessionInfoNotException();
|
}catch(Exception e){
|
return null;
|
}
|
}
|
|
/**
|
* 获取当前线程中的用户对象
|
* @return 当前用户信息
|
* @throws VciBaseException 没有登录会抛出异常
|
*/
|
public static SessionInfo getCurrentUserSessionInfo() throws VciBaseException {
|
SessionInfo si= getCurrentUserSessionInfoNotException();
|
if(si==null){
|
throw new VciBaseException("noLogin",new String[]{"没有当前用户信息"});
|
}
|
return si;
|
}
|
|
/**
|
* 获取当前线程中的用户对象
|
* @return 用户对象,但是不抛出异常
|
*/
|
public static SessionInfo getCurrentUserSessionInfoNotException() {
|
return WebThreadLocalUtil.getCurrentUserSessionInfoInThread().get();
|
}
|
|
/**
|
* 设置用户的会话信息对象
|
* @param sessionInfo 会话信息
|
*/
|
public static synchronized void setSessionInfo(SessionInfo sessionInfo){
|
WebThreadLocalUtil.getCurrentUserSessionInfoInThread().set(sessionInfo);
|
}
|
|
/**
|
* 是否设置了corba需要使用的上下文信息,只针对webService的
|
*/
|
private static volatile boolean isSetContext = false;
|
|
/**
|
* 获取IP地址,通过request
|
* @param request 请求的对象
|
* @return ip地址
|
*/
|
public static String getClientInfo(HttpServletRequest request){
|
String ip = request.getHeader("X-Forwarded-For");
|
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
|
ip = request.getHeader("Proxy-Client-IP");
|
}
|
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
|
ip = request.getHeader("WL-Proxy-Client-IP");
|
}
|
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
|
ip = request.getHeader("HTTP_CLIENT_IP");
|
}
|
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
|
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
|
}
|
if (StringUtils.isBlank(ip) || "unknown".equalsIgnoreCase(ip)) {
|
ip = request.getRemoteAddr();
|
}
|
if (StringUtils.isBlank(ip) || ip.indexOf("0:0:0:0:0:0:0:1") >-1) {//0:0:0:0:0:0:0:1是本机在访问
|
ip = "127.0.0.1";
|
}
|
return ip;
|
}
|
|
/**
|
* 设置是否持久化
|
* @param isPersistence 是否持久化
|
*/
|
public static void setPersistence(boolean isPersistence){
|
if(!isPersistence){
|
needPersistenceInThread.set("false");
|
}else{
|
needPersistenceInThread.set("");
|
}
|
}
|
|
|
/**
|
* 将对象转换为字符串出来
|
* @return json字符串
|
*/
|
public static String getJSONStringWithDateFormat(Object obj){
|
return JSONObject.toJSONStringWithDateFormat(obj, VciDateUtil.DateTimeMillFormat, SerializerFeature.WriteDateUseDateFormat);
|
}
|
|
/**
|
* 最新转换为map
|
* @param o 对象
|
* @return map
|
*/
|
public static Map<String,Object> objectToMap(Object o){
|
Map<String,Object> map = new HashMap<String,Object>();
|
if(o!=null) {
|
String jsonString = JSONObject.toJSONStringWithDateFormat(o, VciDateUtil.DateTimeMillFormat, SerializerFeature.WriteDateUseDateFormat);
|
if(StringUtils.isNotBlank(jsonString)) {
|
JSONObject jsonObject = JSONObject.parseObject(jsonString);
|
if(jsonObject!=null){
|
for(String key : jsonObject.keySet()){
|
map.put(key,jsonObject.get(key));
|
}
|
}
|
}
|
}
|
return map;
|
}
|
|
/**
|
* 对象转换为map
|
* @param o 对象
|
* @return map
|
*/
|
public static Map<String,String> objectToMapString(Object o){
|
Map<String,String> map = new HashMap<String,String>();
|
if(o!=null) {
|
String jsonString = JSONObject.toJSONStringWithDateFormat(o, VciDateUtil.DateTimeMillFormat, SerializerFeature.WriteDateUseDateFormat);
|
if(StringUtils.isNotBlank(jsonString)) {
|
JSONObject jsonObject = JSONObject.parseObject(jsonString);
|
if(jsonObject!=null){
|
for(String key : jsonObject.keySet()){
|
map.put(key,jsonObject.getString(key));
|
}
|
}
|
}
|
}
|
return map;
|
}
|
|
/**
|
* 判断某个属性是否为空
|
* @param obj 对象
|
* @param f 字段
|
* @return true是不空
|
*/
|
public static boolean isNotNullForField(Object obj,Field f){
|
if(!"serialVersionUID".equalsIgnoreCase(f.getName()) &&!"DEFAULT_INITIAL_CAPACITY".equalsIgnoreCase(f.getName())&&null!=obj && !WebUtil.isNullOrNullString(obj.toString())) {
|
return true;
|
} else {
|
return false;
|
}
|
}
|
|
/**
|
* 数组转换为字符串
|
* @param array 数组
|
* @return 字符串
|
*/
|
public static String array2String(String[] array) {
|
if(null == array || array.length == 0) {
|
return "";
|
}else{
|
return Arrays.stream(array).collect(Collectors.joining(","));
|
}
|
}
|
|
/**
|
* 对象转换为字符串
|
* @param obj 对象
|
* @return 字符串
|
*/
|
public static String getString(Object obj){
|
if(obj == null) {
|
return "";
|
}
|
if(obj instanceof Date) {
|
return VciDateUtil.date2Str((Date) obj, VciDateUtil.DateTimeFormat);
|
}
|
return String.valueOf(obj);
|
}
|
|
/**
|
* 拷贝map里的值
|
* @param source 源
|
* @param target 目标
|
* @param copyField 拷贝的属性
|
*/
|
public static void copyValueForMap(Map source,Map target,String[] copyField){
|
Map<String,String> copyFieldMap = new HashMap<String,String>();
|
for(String field : copyField) {
|
copyFieldMap.put(field, field);
|
}
|
copyValueForMap(source,target,copyFieldMap);
|
}
|
/**
|
* 为map拷贝值
|
* @param source 源
|
* @param target 目标
|
* @param copyField key为目标对象里的字段,
|
*/
|
public static void copyValueForMap(Map source,Map target,Map<String,String> copyField){
|
try{
|
Iterator<String> it = copyField.keySet().iterator();
|
while(it.hasNext()){
|
String field = it.next();
|
target.put(field, source.get(copyField.get(field)));
|
}
|
}catch(Exception e){
|
if(logger.isErrorEnabled()){
|
logger.error("拷贝值到map",e);
|
}
|
}
|
}
|
|
/**
|
* 从Map里获取double类型
|
* @param field 字段名称
|
* @param record map
|
* @return 属性
|
*/
|
public static Double getDoubleFromMap(String field,
|
Map<String, Object> record) {
|
if(WebUtil.isNullOrNullString(field) || record == null || !record.containsKey(field)) {
|
return null;
|
}else{
|
Object v = record.get(field);
|
if(v instanceof BigDecimal){
|
return ((BigDecimal)v).doubleValue();
|
}else if(v instanceof Double){
|
return ((Double)v).doubleValue();
|
}else{
|
return WebUtil.getDouble((String)v);
|
}
|
}
|
}
|
|
/**
|
* 获取不是空值的映射,且key是小写
|
* @param map 映射
|
* @return 去除空值的
|
*/
|
public static Map getNotNullMap(Map map){
|
if(map == null){
|
return new HashMap();
|
}
|
Iterator it = map.keySet().iterator();
|
Map unNullMap = new HashMap();
|
while(it.hasNext()){
|
Object key = it.next();
|
String newKey = key.toString().toLowerCase();
|
Object value = map.get(key);
|
if(value !=null){
|
if(value instanceof String && WebUtil.isNotNull(value.toString())){
|
unNullMap.put(newKey, value);
|
}else if(!(value instanceof String)){
|
unNullMap.put(newKey, value);
|
}
|
}
|
}
|
return unNullMap;
|
}
|
|
/**
|
* 获取集合的元素类型
|
* @param field 属性
|
* @return 元素类型, 不是集合的时候返回Null
|
*/
|
public static Class getCollectionElementClass(Field field) throws VciBaseException{
|
Class fieldClass = null;
|
if(field == null){
|
return null;
|
}
|
if(field.getType().isAssignableFrom(List.class) ||
|
field.getType().isAssignableFrom(Set.class) ||
|
field.getType().isAssignableFrom(Vector.class)){
|
Type fc = field.getGenericType();
|
if(fc instanceof ParameterizedType){
|
ParameterizedType pt = (ParameterizedType)fc;
|
fieldClass= (Class)pt.getActualTypeArguments()[0];
|
}
|
}
|
return fieldClass;
|
}
|
|
/**
|
* 获取对象中的所有属性,包括其继承的属性
|
* @param c 对象
|
* @return 所有的属性
|
*/
|
public static List<Field> getAllFieldForObj(Class c){
|
List<Field> allField = new ArrayList<Field>();
|
for(Class<?> classz = c ; classz != Object.class ; classz = classz.getSuperclass() ){
|
Field[] thisClassField = classz.getDeclaredFields();
|
for(Field field : thisClassField){
|
if(!field.getName().equals("serialVersionUID")){
|
if(!allField.contains(field)){
|
allField.add(field);
|
}
|
}
|
}
|
}
|
return allField;
|
}
|
|
/**
|
* 获取ts的字段
|
* @param c 对象所属的类
|
* @return 时间戳的对象
|
*/
|
public static Field getTsField(Class c){
|
List<Field> allField = getAllFieldForObj(c);
|
if(allField!=null&&allField.size()>0){
|
for(Field field : allField){
|
if(field.getName().equals("ts")){
|
return field;
|
}
|
}
|
}
|
return null;
|
}
|
|
/**
|
* 根据名称获取字段
|
* @param field 字段的名称
|
* @param obj 对象
|
* @return 字段对象
|
*/
|
public static Field getFieldForObject(String field,Object obj){
|
if(obj == null){
|
return null;
|
}
|
return getFieldForObject(field,obj.getClass());
|
}
|
|
/**
|
* 根据名称获取字段
|
* @param fieldName 字段的名称
|
* @param c 对象类型
|
* @return 字段对象
|
*/
|
public static Field getFieldForObject(String fieldName,Class c){
|
List<Field> allField = getAllFieldForObj(c);
|
if(allField!=null&&allField.size()>0){
|
for(Field field : allField){
|
if(field.getName().toLowerCase().equalsIgnoreCase(fieldName.toLowerCase())){
|
return field;
|
}
|
}
|
}
|
return null;
|
}
|
|
/**
|
* 获取字段的setter
|
* @param c 对象类
|
* @param field 字段
|
* @return 方法
|
*/
|
public static Method getSetmethod(Class c,Field field){
|
return getSetmethod(c,field.getName());
|
}
|
|
/**
|
* 获取字段的setter
|
* @param c 对象类型
|
* @param fieldName 字段名称
|
* @return 方法
|
*/
|
public static Method getSetmethod(Class c,String fieldName){
|
if(c!=null&&isNotNull(fieldName)){
|
try {
|
PropertyDescriptor pd = new PropertyDescriptor(fieldName, c);
|
return pd.getWriteMethod();
|
} catch (SecurityException e) {
|
} catch (IntrospectionException e) {
|
}
|
}
|
return null;
|
}
|
|
/**
|
* 获取字段的getter
|
* @param c 对象类型
|
* @param fieldName 字段名称
|
* @return 方法
|
*/
|
public static Method getGetmethod(Class c,String fieldName){
|
if(c!=null&&isNotNull(fieldName)){
|
try {
|
PropertyDescriptor pd = new PropertyDescriptor(fieldName, c);
|
return pd.getReadMethod();
|
} catch (SecurityException e) {
|
} catch (IntrospectionException e) {
|
}
|
}
|
return null;
|
}
|
|
/**
|
* 获取字段的getter
|
* @param c 对象类型
|
* @param field 字段
|
* @return 方法
|
*/
|
public static Method getGetmethod(Class c,Field field){
|
return getGetmethod(c,field.getName());
|
}
|
|
/**
|
* 获取对象转换字符串
|
* @param obj 对象
|
* @return 字符串
|
*/
|
public static String getStringValueFromObject(Object obj){
|
if(obj == null){
|
return "";
|
}else{
|
if(obj instanceof Integer || obj instanceof Float || obj instanceof Long || obj instanceof Double){
|
return String.valueOf(obj);
|
}else if(obj instanceof Date){
|
return VciDateUtil.date2Str((Date)obj, VciDateUtil.DateTimeMillFormat);
|
}else{
|
return obj.toString();
|
}
|
}
|
}
|
|
/**
|
* 为对象赋值,不判断类型,属性是什么类型的,value就必须是什么类型
|
* @param fieldName 属性名称
|
* @param targetObject 对象
|
* @param value 属性值
|
*/
|
public static void setValueToField(String fieldName,Object targetObject,Object value){
|
if(isNotNull(fieldName)){
|
Method setMethod = getSetmethod(targetObject.getClass(), fieldName);
|
try {
|
if(setMethod != null){
|
setMethod.invoke(targetObject, value);
|
}else{
|
Field field = getFieldForObject(fieldName, targetObject);
|
if(field !=null){
|
field.setAccessible(true);
|
field.set(targetObject, value);
|
}
|
}
|
} catch (IllegalArgumentException e) {
|
if(logger.isErrorEnabled()){
|
logger.error("WebUtil.setValueToField",e);
|
}
|
} catch (IllegalAccessException e) {
|
if(logger.isErrorEnabled()){
|
logger.error("WebUtil.setValueToField",e);
|
}
|
} catch (InvocationTargetException e) {
|
if(logger.isErrorEnabled()){
|
logger.error("WebUtil.setValueToField",e);
|
}
|
}
|
}
|
}
|
|
/**
|
* 从对象上获取属性的值
|
* @param fieldName 属性名
|
* @param sourceObject 对象
|
* @return 值
|
*/
|
public static Object getValueFromField(String fieldName,Object sourceObject){
|
if(isNotNull(fieldName)){
|
try {
|
Method getMethod = getGetmethod(sourceObject.getClass(), fieldName);
|
if(getMethod !=null){
|
return getMethod.invoke(sourceObject);
|
}else{
|
//说明没有设置getter,比如BO和LO对象这种
|
Field field = getFieldForObject(fieldName, sourceObject);
|
if(field !=null){
|
field.setAccessible(true);
|
return field.get(sourceObject);
|
}
|
}
|
} catch (SecurityException e) {
|
if(logger.isErrorEnabled()){
|
logger.error("WebUtil.getValueFromField",e);
|
}
|
} catch (IllegalAccessException e) {
|
if(logger.isErrorEnabled()){
|
logger.error("WebUtil.getValueFromField",e);
|
}
|
} catch (IllegalArgumentException e) {
|
if(logger.isErrorEnabled()){
|
logger.error("WebUtil.getValueFromField",e);
|
}
|
} catch (InvocationTargetException e) {
|
if(logger.isErrorEnabled()){
|
logger.error("WebUtil.getValueFromField",e);
|
}
|
}
|
}
|
return null;
|
}
|
|
/**
|
* 是否为普通的属性
|
* @param attrName 属性的名字
|
* @return true
|
*/
|
public static boolean isNormalAttr(String attrName){
|
attrName = attrName.toLowerCase();
|
if(attrName.indexOf(".")<0 && attrName.indexOf("_")<0 && !attrName.equalsIgnoreCase("lcstatustext")){
|
return true;
|
}else{
|
return false;
|
}
|
}
|
|
|
/**
|
* 将whereSql里的内容转化到查询map里
|
* @param whereSql sql转换为map
|
* @return map
|
*/
|
public static Map<String,String> whereSql2Map(
|
String whereSql) {
|
Map<String,String> map = new HashMap<String, String>();
|
if(isNotNull(whereSql)){
|
String[] selects = whereSql.split("and");
|
if(selects!=null&&selects.length>0){
|
for(String s : selects){
|
s = s.trim();
|
map.put(s.substring(0,s.indexOf(" ")).trim(), s.substring(s.indexOf(" ") +1).trim());
|
}
|
}
|
}
|
return map;
|
}
|
|
/**
|
* 本机的ip
|
*/
|
private static String localIp = null;
|
|
/**
|
* 获取本机地址,不是客户端电脑的ip,是当前服务所在的ip
|
* @return
|
*/
|
public static String getLocalIp(){
|
if(localIp == null){
|
try {
|
InetAddress inetAddress = getLocalHostLANAddress();
|
if (inetAddress == null) {
|
localIp = "127.0.0.1";
|
} else {
|
localIp = inetAddress.getHostAddress();
|
}
|
}catch (Exception e){
|
localIp = "127.0.0.1";
|
}
|
}
|
return localIp;
|
}
|
|
/**
|
* 从网络接口上获取ip地址
|
* @return ip地址
|
*/
|
private static InetAddress getLocalHostLANAddress(){
|
try {
|
InetAddress candidateAddress = null;
|
// 遍历所有的网络接口
|
for (Enumeration ifaces = NetworkInterface.getNetworkInterfaces(); ifaces.hasMoreElements(); ) {
|
NetworkInterface iface = (NetworkInterface) ifaces.nextElement();
|
// 在所有的接口下再遍历IP
|
for (Enumeration inetAddrs = iface.getInetAddresses(); inetAddrs.hasMoreElements(); ) {
|
InetAddress inetAddr = (InetAddress) inetAddrs.nextElement();
|
if (!inetAddr.isLoopbackAddress()) {// 排除loopback类型地址
|
if (inetAddr.isSiteLocalAddress()) {
|
// 如果是site-local地址,就是它了
|
return inetAddr;
|
} else if (candidateAddress == null) {
|
// site-local类型的地址未被发现,先记录候选地址
|
candidateAddress = inetAddr;
|
}
|
}
|
}
|
}
|
if (candidateAddress != null) {
|
return candidateAddress;
|
}
|
// 如果没有发现 non-loopback地址.只能用最次选的方案
|
InetAddress jdkSuppliedAddress = InetAddress.getLocalHost();
|
return jdkSuppliedAddress;
|
} catch (Exception e) {
|
if(logger.isErrorEnabled()){
|
logger.error("获取本机ip",e);
|
}
|
}
|
return null;
|
}
|
|
/**
|
* oracle in 查询不能超过1000,转换一下集合
|
* 由于SQL语句1000个可能很长,超过oracle10g,所以牺牲性能分配为500个数组
|
* @param list 需要转换的列表内容
|
* @return 分组后的list
|
*/
|
public static <T> Collection<Collection<T>> switchCollectionForOracleIn(Collection<T> list) {
|
return switchCollectionForOracleIn(list,500);
|
}
|
|
/**
|
* 转换集合的大小,这个用在feign调用的时候,不要在sql查询的时候使用
|
* @param collection 需要转换的列表内容
|
* @param preSize 每个分组的大小
|
* @return 分组后的list
|
*/
|
public static <T> Collection<Collection<T>> switchCollectionForOracleIn(Collection<T> collection,int preSize) {
|
Collection<Collection<T>> listHasList = new ArrayList<Collection<T>>();
|
if(collection == null){
|
return listHasList;
|
}
|
List<T> newList = new ArrayList<T>();
|
for(Object obj : collection){
|
//为了让list还可以添加内容,因为使用sublist后,list不能再Add了
|
newList.add((T)obj);
|
}
|
int muti = 1;
|
if(newList.size() >preSize){
|
int balance = newList.size()%preSize;
|
muti = (newList.size() - balance)/preSize + (balance == 0?0:1);
|
}
|
for(int i = 0 ; i < muti; i ++){
|
int start = i*preSize;
|
int end = start + preSize;
|
if(i == muti-1 || end >newList.size() ){
|
end = newList.size();
|
}
|
List subList = newList.subList(start,end);
|
listHasList.add(subList);
|
}
|
return listHasList;
|
}
|
|
}
|