上传代码
This commit is contained in:
45
src/main/java/com/nis/util/AsciiJudge.java
Normal file
45
src/main/java/com/nis/util/AsciiJudge.java
Normal file
@@ -0,0 +1,45 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 判断关键字的内容不能包含空格、tab、回车等不可见字符,即ANSII范围0x00至0x1F(0-31)及0x7F(127)。
|
||||
*
|
||||
* @author RenKaiGe-Office
|
||||
*
|
||||
*/
|
||||
public class AsciiJudge {
|
||||
|
||||
public static void main(String[] args) {
|
||||
String str = "fdsf你说说你发的是佛山东方啥的飞sdf 啥打法是否(\\&)";
|
||||
boolean bool = asciiControlChar(str);
|
||||
System.out.println(bool);
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断字符串是否包含控制字符
|
||||
*
|
||||
* @param str
|
||||
* 需要验证的字符串,可以为空字符串但是不能为null
|
||||
* @return true代表包含控制字符,false代表不是控制字符或为null
|
||||
*/
|
||||
public static boolean asciiControlChar(String str) {
|
||||
if (null != str) {
|
||||
List<String> list = new ArrayList<String>();
|
||||
for (int i = 0; i < 32; i++) {
|
||||
list.add(String.valueOf(i));
|
||||
}
|
||||
list.add("127");
|
||||
char[] charArr = str.toCharArray();
|
||||
for (char c : charArr) {
|
||||
String num = Integer.valueOf(c).toString();
|
||||
if (list.contains(num)) {
|
||||
return true;
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
199
src/main/java/com/nis/util/BasicProvingUtil.java
Normal file
199
src/main/java/com/nis/util/BasicProvingUtil.java
Normal file
@@ -0,0 +1,199 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.net.Inet4Address;
|
||||
import java.net.Inet6Address;
|
||||
import java.net.InetAddress;
|
||||
import java.net.UnknownHostException;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
public class BasicProvingUtil {
|
||||
public static void main(String[] args) {
|
||||
// String ip = "::";
|
||||
String ip = " fe80::d025:864c:3151:daa0";
|
||||
System.out.println(ip + "=" + isIpv6(ip));
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否是Integer类型
|
||||
*
|
||||
* @param obj
|
||||
* @return
|
||||
*/
|
||||
public static boolean isIntType(Object obj) {
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
String num = obj.toString().trim();
|
||||
if (num.length() == 0) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Integer.parseInt(num);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否是Long类型
|
||||
*
|
||||
* @param obj
|
||||
* @return
|
||||
*/
|
||||
public static boolean isLongType(Object obj) {
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
String num = obj.toString().trim();
|
||||
if (num.length() == 0) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Long.parseLong(num);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否是Double类型
|
||||
*
|
||||
* @param obj
|
||||
* @return
|
||||
*/
|
||||
public static boolean isDoubleType(Object obj) {
|
||||
if (obj == null) {
|
||||
return false;
|
||||
}
|
||||
String num = obj.toString().trim();
|
||||
if (num.length() == 0) {
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
Double.parseDouble(num);
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断ip或ip掩码格式是否正确(ipv4或ipv6) true代表格式正确 false代表格式不正确
|
||||
*
|
||||
* @param ip
|
||||
* @param ipType
|
||||
* ipv4还是ipv6(4,6)
|
||||
* @return
|
||||
*/
|
||||
public static boolean isIpOrIpMask(String ip, Integer ipType) {
|
||||
// boolean ipv4Bool = val_ipv4(ip);
|
||||
// boolean ipv6Bool = val_ipv6(ip);
|
||||
// if (ipv6Bool) {
|
||||
|
||||
if (null != ip && !ip.equals("")) {
|
||||
if (null != ipType && ipType == 4) {
|
||||
boolean ipv4 = isIpv4(ip.trim());
|
||||
if (ipv4) {
|
||||
return true;
|
||||
}
|
||||
} else if (null != ipType && ipType == 6) {
|
||||
boolean ipv6 = isIpv6(ip.trim());
|
||||
if (ipv6) {
|
||||
return true;
|
||||
}
|
||||
|
||||
} else {// ipType不等于4或6时不验证与ipType是否一致,仅验证是否是ip格式
|
||||
boolean ipv6 = isIpv6(ip.trim());
|
||||
boolean ipv4 = isIpv4(ip.trim());
|
||||
if (ipv6 || ipv4) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断端口或端口掩码格式是否正确(0-65535) true代表格式正确 false代表格式不正确
|
||||
*
|
||||
* @param ip
|
||||
* @return
|
||||
*/
|
||||
public static boolean isPortOrPortMask(String port) {
|
||||
try {
|
||||
if (null != port && !port.equals("")) {
|
||||
int parseInt = Integer.parseInt(port.trim());
|
||||
if (parseInt >= 0 && parseInt <= 65535) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isIpv4(String ipAddress) {
|
||||
try {
|
||||
String ipv4 = "^(0|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
|
||||
+ "(0|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\." + "(0|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
|
||||
+ "(0|1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";
|
||||
return Pattern.compile(ipv4).matcher(ipAddress).matches();
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean isIpv6(String ipAddress) {
|
||||
try {
|
||||
|
||||
String ipv6 = "^((::)|(([0-9A-Fa-f]{1,4}:){7}[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){1,7}:)|(([0-9A-Fa-f]{1,4}:){6}:[0-9A-Fa-f]{1,4})|(([0-9A-Fa-f]{1,4}:){5}(:[0-9A-Fa-f]{1,4}){1,2})|(([0-9A-Fa-f]{1,4}:){4}(:[0-9A-Fa-f]{1,4}){1,3})|(([0-9A-Fa-f]{1,4}:){3}(:[0-9A-Fa-f]{1,4}){1,4})|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){1,5})|([0-9A-Fa-f]{1,4}:(:[0-9A-Fa-f]{1,4}){1,6})|(:(:[0-9A-Fa-f]{1,4}){1,7})|(([0-9A-Fa-f]{1,4}:){6}(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3})|(([0-9A-Fa-f]{1,4}:){5}:(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3})|(([0-9A-Fa-f]{1,4}:){4}(:[0-9A-Fa-f]{1,4}){0,1}:(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3})|(([0-9A-Fa-f]{1,4}:){3}(:[0-9A-Fa-f]{1,4}){0,2}:(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3})|(([0-9A-Fa-f]{1,4}:){2}(:[0-9A-Fa-f]{1,4}){0,3}:(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3})|([0-9A-Fa-f]{1,4}:(:[0-9A-Fa-f]{1,4}){0,4}:(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3})|(:(:[0-9A-Fa-f]{1,4}){0,5}:(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])(\\.(\\d|[1-9]\\d|1\\d{2}|2[0-4]\\d|25[0-5])){3}))$";
|
||||
return Pattern.compile(ipv6).matcher(ipAddress).matches();
|
||||
} catch (Exception e) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static boolean val_ipv4(String host) {
|
||||
InetAddress addressIpv4 = null;
|
||||
|
||||
try {
|
||||
addressIpv4 = InetAddress.getByName(host);
|
||||
} catch (UnknownHostException e) {
|
||||
return false;
|
||||
}
|
||||
if (addressIpv4 instanceof Inet6Address) {
|
||||
return false;
|
||||
}
|
||||
if (addressIpv4 instanceof Inet4Address) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static boolean val_ipv6(String host) {
|
||||
InetAddress addressIpv6 = null;
|
||||
try {
|
||||
addressIpv6 = InetAddress.getByName(host);
|
||||
} catch (UnknownHostException e) {
|
||||
e.printStackTrace();
|
||||
return false;
|
||||
}
|
||||
if (addressIpv6 instanceof Inet6Address) {
|
||||
return true;
|
||||
}
|
||||
if (addressIpv6 instanceof Inet4Address) {
|
||||
return false;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
154
src/main/java/com/nis/util/BeanHelper.java
Normal file
154
src/main/java/com/nis/util/BeanHelper.java
Normal file
@@ -0,0 +1,154 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.beans.BeanInfo;
|
||||
import java.beans.IntrospectionException;
|
||||
import java.beans.Introspector;
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
/**
|
||||
*
|
||||
* <p>Title:BeanHelper</p>
|
||||
* <p>Description:去除Bean中String类型字段的前后空格</p>
|
||||
*
|
||||
* @author:RKG
|
||||
* @Date:2016-4-29
|
||||
*/
|
||||
public class BeanHelper {
|
||||
|
||||
/**
|
||||
* 去掉bean中所有属性为字符串的前后空格
|
||||
*
|
||||
* @param bean
|
||||
* @throws Exception
|
||||
*/
|
||||
public static void beanAttributeValueTrim(Object bean) throws Exception {
|
||||
if (bean != null) {
|
||||
// 获取所有的字段包括public,private,protected,private
|
||||
Field[] fields = bean.getClass().getDeclaredFields();
|
||||
for (int i = 0; i < fields.length; i++) {
|
||||
Field f = fields[i];
|
||||
if (f.getType().getName().equals("java.lang.String")) {
|
||||
String key = f.getName();// 获取字段名
|
||||
Object value = getFieldValue(bean, key);
|
||||
|
||||
if (value == null)
|
||||
continue;
|
||||
setFieldValue(bean, key, value.toString().trim());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 利用反射通过get方法获取bean中字段fieldName的值
|
||||
*
|
||||
* @param bean
|
||||
* @param fieldName
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
private static Object getFieldValue(Object bean, String fieldName)
|
||||
throws Exception {
|
||||
StringBuffer result = new StringBuffer();
|
||||
String methodName = result.append("get")
|
||||
.append(fieldName.substring(0, 1).toUpperCase())
|
||||
.append(fieldName.substring(1)).toString();
|
||||
|
||||
Object rObject = null;
|
||||
Method method = null;
|
||||
|
||||
@SuppressWarnings("rawtypes")
|
||||
Class[] classArr = new Class[0];
|
||||
method = bean.getClass().getMethod(methodName, classArr);
|
||||
rObject = method.invoke(bean, new Object[0]);
|
||||
|
||||
return rObject;
|
||||
}
|
||||
|
||||
/**
|
||||
* 利用发射调用bean.set方法将value设置到字段
|
||||
*
|
||||
* @param bean
|
||||
* @param fieldName
|
||||
* @param value
|
||||
* @throws Exception
|
||||
*/
|
||||
private static void setFieldValue(Object bean, String fieldName,
|
||||
Object value) throws Exception {
|
||||
StringBuffer result = new StringBuffer();
|
||||
String methodName = result.append("set")
|
||||
.append(fieldName.substring(0, 1).toUpperCase())
|
||||
.append(fieldName.substring(1)).toString();
|
||||
|
||||
/**
|
||||
* 利用发射调用bean.set方法将value设置到字段
|
||||
*/
|
||||
Class[] classArr = new Class[1];
|
||||
classArr[0] = "java.lang.String".getClass();
|
||||
Method method = bean.getClass().getMethod(methodName, classArr);
|
||||
method.invoke(bean, value);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* transportBean2Map(将Java bean转换为Map)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param clazz
|
||||
* @param obj
|
||||
* @return
|
||||
* @throws IntrospectionException
|
||||
*Map<String,String>
|
||||
* @throws InvocationTargetException
|
||||
* @throws IllegalArgumentException
|
||||
* @throws IllegalAccessException
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public static Map<String,String> transportBean2Map(Class clazz,Object obj) throws IntrospectionException, IllegalAccessException, IllegalArgumentException, InvocationTargetException{
|
||||
Map<String,String> bean=new LinkedHashMap<>();
|
||||
BeanInfo beanInfo=Introspector.getBeanInfo(clazz);
|
||||
PropertyDescriptor[] propertyDescriptors=beanInfo.getPropertyDescriptors();
|
||||
for(PropertyDescriptor propertyDescriptor:propertyDescriptors){
|
||||
String key =propertyDescriptor.getName();
|
||||
if(!key.equals("class")){
|
||||
String _value=null;
|
||||
Method getter=propertyDescriptor.getReadMethod();
|
||||
Object value =getter.invoke(obj);
|
||||
if(value==null) continue;
|
||||
else if(value instanceof java.util.Date)//时间类型转换成long
|
||||
_value=String.valueOf(((java.util.Date)value).getTime());
|
||||
else if(value instanceof Boolean||value instanceof Integer||value instanceof Long){
|
||||
_value=String.valueOf(value);
|
||||
}else if(value instanceof String){
|
||||
_value=(String)value;
|
||||
}else if(value instanceof Collection){
|
||||
throw new RuntimeException("不支持对象中嵌套的对象集合");
|
||||
}else{
|
||||
|
||||
}
|
||||
if(_value!=null)
|
||||
bean.put(key, _value);
|
||||
}
|
||||
|
||||
}
|
||||
return bean;
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
// SrcIp ip=new SrcIp();
|
||||
// ip.setAreaId(1l);
|
||||
// try {
|
||||
// Map<String,String> transportBean2Map=transportBean2Map(SrcIp.class,ip);
|
||||
// System.out.println(transportBean2Map.size());
|
||||
// for(Entry<String, String> e:transportBean2Map.entrySet()){
|
||||
// System.out.println(e.getKey()+" "+e.getValue());
|
||||
// }
|
||||
// } catch (IntrospectionException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
|
||||
// // TODO Auto-generated catch block
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
}
|
||||
}
|
||||
97
src/main/java/com/nis/util/CacheUtils.java
Normal file
97
src/main/java/com/nis/util/CacheUtils.java
Normal file
@@ -0,0 +1,97 @@
|
||||
package com.nis.util;
|
||||
|
||||
import com.nis.web.service.SpringContextHolder;
|
||||
|
||||
import net.sf.ehcache.Cache;
|
||||
import net.sf.ehcache.CacheManager;
|
||||
import net.sf.ehcache.Element;
|
||||
|
||||
/**
|
||||
* Cache工具类
|
||||
* @author darnell
|
||||
*
|
||||
*/
|
||||
public class CacheUtils {
|
||||
|
||||
private static CacheManager cacheManager = ((CacheManager)SpringContextHolder.getBean("cacheManager"));
|
||||
|
||||
private static final String SYS_CACHE = "sysCache";
|
||||
|
||||
/**
|
||||
* 获取SYS_CACHE缓存
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static Object get(String key) {
|
||||
return get(SYS_CACHE, key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入SYS_CACHE缓存
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static void put(String key, Object value) {
|
||||
put(SYS_CACHE, key, value);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从SYS_CACHE缓存中移除
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static void remove(String key) {
|
||||
remove(SYS_CACHE, key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取缓存
|
||||
* @param cacheName
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static Object get(String cacheName, String key) {
|
||||
Element element = getCache(cacheName).get(key);
|
||||
return element==null?null:element.getObjectValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入缓存
|
||||
* @param cacheName
|
||||
* @param key
|
||||
* @param value
|
||||
*/
|
||||
public static void put(String cacheName, String key, Object value) {
|
||||
Element element = new Element(key, value);
|
||||
getCache(cacheName).put(element);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从缓存中移除
|
||||
* @param cacheName
|
||||
* @param key
|
||||
*/
|
||||
public static void remove(String cacheName, String key) {
|
||||
getCache(cacheName).remove(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得一个Cache,没有则创建一个。
|
||||
* @param cacheName
|
||||
* @return
|
||||
*/
|
||||
private static Cache getCache(String cacheName){
|
||||
Cache cache = cacheManager.getCache(cacheName);
|
||||
if (cache == null){
|
||||
cacheManager.addCache(cacheName);
|
||||
cache = cacheManager.getCache(cacheName);
|
||||
cache.getCacheConfiguration().setEternal(true);
|
||||
}
|
||||
return cache;
|
||||
}
|
||||
|
||||
public static CacheManager getCacheManager() {
|
||||
return cacheManager;
|
||||
}
|
||||
|
||||
}
|
||||
176
src/main/java/com/nis/util/Collections3.java
Normal file
176
src/main/java/com/nis/util/Collections3.java
Normal file
@@ -0,0 +1,176 @@
|
||||
/**
|
||||
* Copyright (c) 2005-2012 springside.org.cn
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.beanutils.PropertyUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
/**
|
||||
* Collections工具集.
|
||||
* 在JDK的Collections和Guava的Collections2后, 命名为Collections3.
|
||||
* @author calvin
|
||||
* @version 2013-01-15
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
public class Collections3 {
|
||||
|
||||
/**
|
||||
* 提取集合中的对象的两个属性(通过Getter函数), 组合成Map.
|
||||
*
|
||||
* @param collection 来源集合.
|
||||
* @param keyPropertyName 要提取为Map中的Key值的属性名.
|
||||
* @param valuePropertyName 要提取为Map中的Value值的属性名.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static Map extractToMap(final Collection collection, final String keyPropertyName,
|
||||
final String valuePropertyName) {
|
||||
Map map = new HashMap(collection.size());
|
||||
|
||||
try {
|
||||
for (Object obj : collection) {
|
||||
map.put(PropertyUtils.getProperty(obj, keyPropertyName),
|
||||
PropertyUtils.getProperty(obj, valuePropertyName));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw Reflections.convertReflectionExceptionToUnchecked(e);
|
||||
}
|
||||
|
||||
return map;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取集合中的对象的一个属性(通过Getter函数), 组合成List.
|
||||
*
|
||||
* @param collection 来源集合.
|
||||
* @param propertyName 要提取的属性名.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static List extractToList(final Collection collection, final String propertyName) {
|
||||
List list = new ArrayList(collection.size());
|
||||
|
||||
try {
|
||||
for (Object obj : collection) {
|
||||
list.add(PropertyUtils.getProperty(obj, propertyName));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw Reflections.convertReflectionExceptionToUnchecked(e);
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 提取集合中的对象的一个属性(通过Getter函数), 组合成由分割符分隔的字符串.
|
||||
*
|
||||
* @param collection 来源集合.
|
||||
* @param propertyName 要提取的属性名.
|
||||
* @param separator 分隔符.
|
||||
*/
|
||||
public static String extractToString(final Collection collection, final String propertyName, final String separator) {
|
||||
List list = extractToList(collection, propertyName);
|
||||
return StringUtils.join(list, separator);
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换Collection所有元素(通过toString())为String, 中间以 separator分隔。
|
||||
*/
|
||||
public static String convertToString(final Collection collection, final String separator) {
|
||||
return StringUtils.join(collection, separator);
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换Collection所有元素(通过toString())为String, 每个元素的前面加入prefix,后面加入postfix,如<div>mymessage</div>。
|
||||
*/
|
||||
public static String convertToString(final Collection collection, final String prefix, final String postfix) {
|
||||
StringBuilder builder = new StringBuilder();
|
||||
for (Object o : collection) {
|
||||
builder.append(prefix).append(o).append(postfix);
|
||||
}
|
||||
return builder.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断是否为空.
|
||||
*/
|
||||
public static boolean isEmpty(Collection collection) {
|
||||
return (collection == null || collection.isEmpty());
|
||||
}
|
||||
|
||||
/**
|
||||
* 取得Collection的第一个元素,如果collection为空返回null.
|
||||
*/
|
||||
public static <T> T getFirst(Collection<T> collection) {
|
||||
if (isEmpty(collection)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return collection.iterator().next();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取Collection的最后一个元素 ,如果collection为空返回null.
|
||||
*/
|
||||
public static <T> T getLast(Collection<T> collection) {
|
||||
if (isEmpty(collection)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
//当类型为List时,直接取得最后一个元素 。
|
||||
if (collection instanceof List) {
|
||||
List<T> list = (List<T>) collection;
|
||||
return list.get(list.size() - 1);
|
||||
}
|
||||
|
||||
//其他类型通过iterator滚动到最后一个元素.
|
||||
Iterator<T> iterator = collection.iterator();
|
||||
while (true) {
|
||||
T current = iterator.next();
|
||||
if (!iterator.hasNext()) {
|
||||
return current;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回a+b的新List.
|
||||
*/
|
||||
public static <T> List<T> union(final Collection<T> a, final Collection<T> b) {
|
||||
List<T> result = new ArrayList<T>(a);
|
||||
result.addAll(b);
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回a-b的新List.
|
||||
*/
|
||||
public static <T> List<T> subtract(final Collection<T> a, final Collection<T> b) {
|
||||
List<T> list = new ArrayList<T>(a);
|
||||
for (T element : b) {
|
||||
list.remove(element);
|
||||
}
|
||||
|
||||
return list;
|
||||
}
|
||||
|
||||
/**
|
||||
* 返回a与b的交集的新List.
|
||||
*/
|
||||
public static <T> List<T> intersection(Collection<T> a, Collection<T> b) {
|
||||
List<T> list = new ArrayList<T>();
|
||||
|
||||
for (T element : a) {
|
||||
if (b.contains(element)) {
|
||||
list.add(element);
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
}
|
||||
713
src/main/java/com/nis/util/CompileJudge.java
Normal file
713
src/main/java/com/nis/util/CompileJudge.java
Normal file
@@ -0,0 +1,713 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.nis.domain.restful.ConfigCompile;
|
||||
import com.nis.domain.restful.ConfigGroupRelation;
|
||||
import com.nis.domain.restful.DataDictionaryValue;
|
||||
import com.nis.domain.restful.IpRegion;
|
||||
import com.nis.domain.restful.NumRegion;
|
||||
import com.nis.domain.restful.StrRegion;
|
||||
import com.nis.listener.SystemConfigListener;
|
||||
import com.nis.restful.CompileJudgeCode;
|
||||
import com.nis.web.service.restful.ConfigSourcesService;
|
||||
|
||||
public class CompileJudge {
|
||||
|
||||
/**
|
||||
* 判断当前编译配置中的groupNum属性值与配置分组groupList大小是否小于等于8且大于0
|
||||
*
|
||||
* @param configCompile
|
||||
* 编译配置对象
|
||||
* @return GroupNumAndListLtEight GroupNumGtEight GroupListGtEight
|
||||
* GroupNumEQZero GroupListEQZero
|
||||
*
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("null")
|
||||
public static String groupNumAndListIsOk(ConfigCompile configCompile, boolean isUpdate) {
|
||||
if (null != configCompile) {
|
||||
if (!isUpdate && Constants.BASE_VALIDATE) {
|
||||
String valCompile = valCompile(configCompile);
|
||||
if (!valCompile.equals("ok")) {
|
||||
return valCompile;
|
||||
}
|
||||
}
|
||||
|
||||
if (null == configCompile.getGroupRelationList() && null != configCompile.getCompileId()) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.CompileGroupIsNull.getErrorReason();
|
||||
}
|
||||
if (!isUpdate) {
|
||||
if (null == configCompile.getGroupNum()) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.GroupNumIsNull.getErrorReason();
|
||||
}
|
||||
|
||||
if (configCompile.getGroupNum() > 8) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.GroupNumGtEight.getErrorReason();
|
||||
}
|
||||
|
||||
if (configCompile.getGroupNum() <= 0) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.GroupNumEQZero.getErrorReason();
|
||||
}
|
||||
|
||||
if (null == configCompile.getGroupRelationList()) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.GroupListIsNull.getErrorReason();
|
||||
}
|
||||
|
||||
if (null != configCompile.getGroupRelationList() && configCompile.getGroupRelationList().size() <= 0) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.GroupListEQZero.getErrorReason();
|
||||
}
|
||||
if (null != configCompile.getGroupRelationList() && configCompile.getGroupRelationList().size() > 8) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.GroupListGtEight.getErrorReason();
|
||||
}
|
||||
|
||||
if (configCompile.getGroupRelationList().size() != configCompile.getGroupNum()) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.GroupNumNEQGroupList.getErrorReason();
|
||||
}
|
||||
} else {
|
||||
if (null == configCompile.getCompileId()) {
|
||||
return "compileId字段不能为空";
|
||||
}
|
||||
if (null == configCompile.getGroupRelationList()) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.GroupListIsNull.getErrorReason();
|
||||
}
|
||||
if (configCompile.getIsValid() == 1) {
|
||||
if (null != configCompile.getGroupNum() && configCompile.getGroupNum() > 8) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.GroupNumGtEight.getErrorReason();
|
||||
}
|
||||
if (null != configCompile.getGroupNum() && configCompile.getGroupNum() < 0) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.GroupNumEQZero.getErrorReason();
|
||||
}
|
||||
|
||||
if (null != configCompile.getGroupRelationList()
|
||||
&& configCompile.getGroupRelationList().size() > 8) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.GroupListGtEight.getErrorReason();
|
||||
}
|
||||
|
||||
if (null != configCompile.getGroupRelationList()
|
||||
&& configCompile.getGroupRelationList().size() <= 0) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.GroupListEQZero.getErrorReason();
|
||||
}
|
||||
|
||||
int sizeCount = 0;
|
||||
if (configCompile.getIpRegionList() == null && configCompile.getStrRegionList() == null
|
||||
&& configCompile.getNumRegionList() == null) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.CompileNotNull.getErrorReason();
|
||||
} else {
|
||||
if (configCompile.getIpRegionList() != null) {
|
||||
sizeCount += configCompile.getIpRegionList().size();
|
||||
}
|
||||
if (configCompile.getStrRegionList() != null) {
|
||||
sizeCount += configCompile.getStrRegionList().size();
|
||||
}
|
||||
if (configCompile.getNumRegionList() != null) {
|
||||
sizeCount += configCompile.getNumRegionList().size();
|
||||
}
|
||||
|
||||
if (sizeCount == 0) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.CompileNotNull.getErrorReason();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return CompileJudgeCode.GroupNumAndListLtEight.getErrorReason();
|
||||
} else {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的" + CompileJudgeCode.CompileIsNull.getErrorReason();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断编译配置中所有配置分组内域配置个数是否大于0
|
||||
*
|
||||
* @param configCompile
|
||||
* 编译配置对象
|
||||
* @return CompileGroupSizeGtZero CompileGroupSizeEqZero
|
||||
* CompileGroupIdNotExist CompileGroupIdIsRepeat GroupListEQZero
|
||||
*/
|
||||
public static String compileGroupSizeIsGtZero(ConfigCompile configCompile, boolean isUpdate, StringBuffer sb) {
|
||||
Long compileId = configCompile.getCompileId();
|
||||
List<Long> groupList = new ArrayList<Long>();// 配置分组中groupId集合
|
||||
List<ConfigGroupRelation> groupRelationList = configCompile.getGroupRelationList();
|
||||
// 插入配置时不能是无效
|
||||
if (!isUpdate && configCompile.getIsValid() == 0) {
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置"
|
||||
+ CompileJudgeCode.CompileIsNotInvalid.getErrorReason();
|
||||
}
|
||||
Integer isValid = configCompile.getIsValid();
|
||||
boolean configFlag = false;
|
||||
if (null == groupRelationList) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.CompileGroupIsNull.getErrorReason();
|
||||
}
|
||||
|
||||
if ((!isUpdate) || (isUpdate && configCompile.getIsValid() == 1)) {// 添加或者修改域配置
|
||||
if (groupRelationList.size() > 0) {
|
||||
for (ConfigGroupRelation configGroupRelation : groupRelationList) {
|
||||
if (!isUpdate && Constants.BASE_VALIDATE) {
|
||||
String valCompileGroup = valCompileGroup(configGroupRelation, compileId);
|
||||
if (!valCompileGroup.equals("ok")) {
|
||||
return valCompileGroup;
|
||||
}
|
||||
}
|
||||
|
||||
if (!configGroupRelation.getCompileId().equals(compileId)) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中groupRelationList字段中的compileId为"
|
||||
+ configGroupRelation.getCompileId() + "的配置分组与编译配置id不一致";
|
||||
}
|
||||
if (!groupList.contains(configGroupRelation.getGroupId())) {
|
||||
groupList.add(configGroupRelation.getGroupId());
|
||||
} else {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中groupRelationList存在多个groupid为"
|
||||
+ configGroupRelation.getGroupId() + "的配置分组";
|
||||
}
|
||||
|
||||
if (configGroupRelation.getIsValid() == 0) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中groupRelationList中groupid为"
|
||||
+ configGroupRelation.getGroupId() + "的配置分组不能设置为无效";
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.GroupListEQZero.getErrorReason();
|
||||
}
|
||||
}
|
||||
|
||||
List<Long> regionGroupIdList = new ArrayList<Long>();// 所有域配置中groupId的集合,不重复
|
||||
List<NumRegion> numRegionList = configCompile.getNumRegionList();
|
||||
if (numRegionList == null) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.NumRegionIsNull.getErrorReason();
|
||||
}
|
||||
if (numRegionList.size() > 0) {
|
||||
for (NumRegion numRegion : numRegionList) {
|
||||
// if (configCompile.getIsValid() != 0 &&
|
||||
// !regionGroupIdList.contains(numRegion.getGroupId())) {
|
||||
if (!regionGroupIdList.contains(numRegion.getGroupId())) {
|
||||
regionGroupIdList.add(numRegion.getGroupId());
|
||||
}
|
||||
if (!type2TableNameIsOk(configCompile.getService(), numRegion.getTableName())) {
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置中numRegionList中的regionid为"
|
||||
+ numRegion.getRegionId() + "的域配置tableName与编译配置业务类型不一致";
|
||||
}
|
||||
|
||||
if (!isUpdate && Constants.BASE_VALIDATE) {
|
||||
String valNumRegion = valNumRegion(numRegion, compileId);
|
||||
if (!valNumRegion.equals("ok")) {
|
||||
return valNumRegion;
|
||||
}
|
||||
}
|
||||
|
||||
if (isUpdate && isValid == 1 && numRegion.getIsValid() == 0) {
|
||||
configFlag = true;
|
||||
}
|
||||
if (configCompile.getIsValid() != 0 && !groupList.contains(numRegion.getGroupId())) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中numRegionList中groupid为"
|
||||
+ numRegion.getGroupId() + "的域配置在groupRelationList中不存在";
|
||||
}
|
||||
|
||||
// 插入配置时不能是无效
|
||||
if (!isUpdate && numRegion.getIsValid() == 0) {
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置中numRegionList中的regionid为"
|
||||
+ numRegion.getRegionId() + "的域配置" + CompileJudgeCode.CompileIsNotInvalid.getErrorReason();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
List<StrRegion> strRegionList = configCompile.getStrRegionList();
|
||||
if (strRegionList == null) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.StrRegionIsNull.getErrorReason();
|
||||
}
|
||||
if (strRegionList != null && strRegionList.size() > 0) {
|
||||
for (StrRegion strRegion : strRegionList) {
|
||||
// if (configCompile.getIsValid() != 0 &&
|
||||
// !regionGroupIdList.contains(strRegion.getGroupId())) {
|
||||
if (!regionGroupIdList.contains(strRegion.getGroupId())) {
|
||||
regionGroupIdList.add(strRegion.getGroupId());
|
||||
}
|
||||
if (!type2TableNameIsOk(configCompile.getService(), strRegion.getTableName())) {
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置中strRegionList中的regionid为"
|
||||
+ strRegion.getRegionId() + "的域配置tableName与编译配置业务类型不一致";
|
||||
}
|
||||
if (!isUpdate && Constants.BASE_VALIDATE) {
|
||||
String valStrRegion = valStrRegion(strRegion, compileId,
|
||||
ConfigSourcesService.isStrStrongRegion(strRegion.getTableName()));
|
||||
if (!valStrRegion.equals("ok")) {
|
||||
return valStrRegion;
|
||||
}
|
||||
}
|
||||
if (!isUpdate && Constants.SERVICE_VALIDATE) {
|
||||
String serviceStrRegionVal = serviceStrRegionVal(strRegion, compileId);
|
||||
if (!serviceStrRegionVal.equals("ok")) {
|
||||
return serviceStrRegionVal;
|
||||
}
|
||||
}
|
||||
if (isUpdate && isValid == 1 && strRegion.getIsValid() == 0) {
|
||||
configFlag = true;
|
||||
}
|
||||
if (configCompile.getIsValid() != 0 && !groupList.contains(strRegion.getGroupId())) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中strRegionList中groupid为"
|
||||
+ strRegion.getGroupId() + "的域配置在groupRelationList中不存在";
|
||||
}
|
||||
|
||||
// 插入配置时不能是无效
|
||||
if (!isUpdate && strRegion.getIsValid() == 0) {
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置中strRegionList中的regionid为"
|
||||
+ strRegion.getRegionId() + "的域配置" + CompileJudgeCode.CompileIsNotInvalid.getErrorReason();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
List<IpRegion> ipRegionList = configCompile.getIpRegionList();
|
||||
|
||||
if (ipRegionList == null) {
|
||||
return CompileJudgeCode.IpRegionIsNull.getErrorReason();
|
||||
}
|
||||
if (ipRegionList != null && ipRegionList.size() > 0) {
|
||||
for (IpRegion ipRegion : ipRegionList) {
|
||||
// if (configCompile.getIsValid() != 0 &&
|
||||
// !regionGroupIdList.contains(ipRegion.getGroupId())) {
|
||||
if (!regionGroupIdList.contains(ipRegion.getGroupId())) {
|
||||
regionGroupIdList.add(ipRegion.getGroupId());
|
||||
}
|
||||
|
||||
if (!type2TableNameIsOk(configCompile.getService(), ipRegion.getTableName())) {
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置中ipRegionList中的regionid为"
|
||||
+ ipRegion.getRegionId() + "的域配置tableName与编译配置业务类型不一致";
|
||||
}
|
||||
if (!isUpdate && Constants.BASE_VALIDATE) {
|
||||
String valIpRegion = valIpRegion(ipRegion, compileId);
|
||||
if (!valIpRegion.equals("ok")) {
|
||||
return valIpRegion;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isUpdate && Constants.SERVICE_VALIDATE) {
|
||||
String serviceIpRegionVal = serviceIpRegionVal(ipRegion, compileId);
|
||||
if (!serviceIpRegionVal.equals("ok")) {
|
||||
return serviceIpRegionVal;
|
||||
}
|
||||
}
|
||||
|
||||
if (isUpdate && isValid == 1 && ipRegion.getIsValid() == 0) {
|
||||
configFlag = true;
|
||||
}
|
||||
if (configCompile.getIsValid() != 0 && !groupList.contains(ipRegion.getGroupId())) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中ipRegionList中groupid为"
|
||||
+ ipRegion.getGroupId() + "的域配置在groupRelationList中不存在";
|
||||
}
|
||||
|
||||
// 插入配置时不能是无效
|
||||
if (!isUpdate && ipRegion.getIsValid() == 0) {
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置中ipRegionList中的regionid为"
|
||||
+ ipRegion.getRegionId() + "的域配置" + CompileJudgeCode.CompileIsNotInvalid.getErrorReason();
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
// if (configCompile.getIsValid() != 0 && regionGroupIdList.size() > 0
|
||||
// && groupList.size() > 0) {// 添加配置或修改域配置时判断配置分组集合中groupId是否都在域配置使用
|
||||
if (groupList.size() > 0) {// 修改域配置时判断配置分组集合中groupId是否都在域配置使用
|
||||
for (Long groupId : groupList) {
|
||||
if (!regionGroupIdList.contains(groupId)) {
|
||||
// setSbStr("配置id为" + configCompile.getCompileId() +
|
||||
// "的配置中配置分组groupid为" + groupId+ "的配置在域配置中未被使用(可能是分组复用情况).",
|
||||
// sb);//20161206业务修改:业务目前不会出现分组复用情形,如果前端传过来的json串出现分组复用情形则直接返回异常提示信息
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置中配置分组groupid为" + groupId + "的配置在域配置中未被使用";
|
||||
}
|
||||
// if (configCompile.getIsValid() != 0 && isUpdate &&
|
||||
// !regionGroupIdList.contains(groupId)) {
|
||||
// return "配置id为" + configCompile.getCompileId() +
|
||||
// "的配置在修改时域配置中的groupid为" + groupId
|
||||
// + "的配置在groupRelationList中不存在";
|
||||
// }
|
||||
}
|
||||
}
|
||||
|
||||
if (regionGroupIdList.size() > 0) {
|
||||
for (Long groupId : regionGroupIdList) {
|
||||
if (!groupList.contains(groupId)) {
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置中域配置中的groupid为" + groupId + "的域配置在配置分组关系中不存在";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (configCompile.getIsValid() != 0 && !isUpdate) {
|
||||
// if (!(regionGroupIdList.size() > 0)) {
|
||||
// return CompileJudgeCode.CompileGroupSizeEqZero;
|
||||
// }
|
||||
if (!(groupList.size() > 0)) {
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置在添加时"
|
||||
+ CompileJudgeCode.GroupListEQZero.getErrorReason();
|
||||
}
|
||||
}
|
||||
|
||||
// 编译为有效 域配置至少有一个为无效
|
||||
if (isUpdate && isValid == 1) {
|
||||
if (!configFlag) {
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置在修改时"
|
||||
+ CompileJudgeCode.CompileIsValide.getErrorReason();
|
||||
}
|
||||
}
|
||||
|
||||
return CompileJudgeCode.CompileGroupSizeGtZero.getErrorReason();
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证业务类型与域配置的表名是否对应
|
||||
*
|
||||
* @param serviceType
|
||||
* @param tableName
|
||||
* @return
|
||||
*/
|
||||
public static boolean type2TableNameIsOk(Long serviceType, String tableName) {
|
||||
if (null != serviceType && null != tableName && !tableName.equals("")) {
|
||||
Map<Integer, Map<String, String>> tableRelation = ConfigSourcesService.getTableRelation();
|
||||
Map<String, String> map = tableRelation.get(serviceType.intValue());
|
||||
if (null != map) {
|
||||
if (map.containsKey(tableName.toUpperCase())) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断当前编译配置中的groupNum属性与配置分组groupList大小是否相等且是否均大于0小于等于8, 且每个配置分组中域配置个数大于0
|
||||
*
|
||||
* @param configCompile
|
||||
* @return GroupNumNEQGroupList GroupNumGtEight GroupListGtEight
|
||||
* GroupNumEQZero GroupListEQZero CompileGroupSizeEqZero
|
||||
* CompileGroupIdNotExist CompileGroupIdIsRepeat CompileIsOk
|
||||
* 只有返回CompileIsOk才说明该条配置正常否则该条配置不正常,可根据枚举中成员的注释具体在返回错误信息
|
||||
*/
|
||||
public static String compileIsOk(ConfigCompile configCompile, boolean isUpdate, StringBuffer sb) {
|
||||
|
||||
String msg1 = groupNumAndListIsOk(configCompile, isUpdate);
|
||||
if (msg1 != CompileJudgeCode.GroupNumAndListLtEight.getErrorReason()) {
|
||||
return msg1;
|
||||
}
|
||||
|
||||
String msg2 = compileGroupSizeIsGtZero(configCompile, isUpdate, sb);
|
||||
if (msg2 != CompileJudgeCode.CompileGroupSizeGtZero.getErrorReason()) {
|
||||
return msg2;
|
||||
}
|
||||
String latentMsg = ",数据中可能存在的问题:";
|
||||
if (sb.length() > 0 && !sb.toString().contains(latentMsg)) {
|
||||
latentMsg = latentMsg + sb.toString();
|
||||
sb.setLength(0);
|
||||
sb.append(latentMsg);
|
||||
}
|
||||
return CompileJudgeCode.CompileIsOk.getErrorReason();
|
||||
}
|
||||
|
||||
public static void setSbStr(String str, StringBuffer sb) {
|
||||
if (sb.length() <= 1024) {
|
||||
sb.append(str);
|
||||
}
|
||||
}
|
||||
|
||||
public static String valCompile(ConfigCompile configCompile) {
|
||||
Long compileId = configCompile.getCompileId();
|
||||
if (null == compileId) {
|
||||
return "compileId字段不能为空";
|
||||
}
|
||||
if (null == configCompile.getService()) {
|
||||
return "id为" + compileId + "的编译配置中service不能为空";
|
||||
}
|
||||
|
||||
if (null == configCompile.getAction()) {
|
||||
return "id为" + compileId + "的编译配置中action不能为空";
|
||||
}
|
||||
if (null == configCompile.getDoBlackList()) {
|
||||
return "id为" + compileId + "的编译配置中doBlackList不能为空";
|
||||
}
|
||||
if (null == configCompile.getDoLog()) {
|
||||
return "id为" + compileId + "的编译配置中doLog不能为空";
|
||||
}
|
||||
if (null == configCompile.getEffectiveRange() || configCompile.getEffectiveRange().equals("")) {
|
||||
return "id为" + compileId + "的编译配置中effectiveRange不能为空";
|
||||
}
|
||||
if (null == configCompile.getConfigPercent()) {
|
||||
return "id为" + compileId + "的编译配置中configPercent不能为空";
|
||||
}
|
||||
if (null == configCompile.getConfigOption()) {
|
||||
return "id为" + compileId + "的编译配置中configOption不能为空";
|
||||
}
|
||||
if (null == configCompile.getStartTime()) {
|
||||
return "id为" + compileId + "的编译配置中startTime不能为空";
|
||||
}
|
||||
if (null == configCompile.getEndTime()) {
|
||||
return "id为" + compileId + "的编译配置中endTime不能为空";
|
||||
}
|
||||
if (null == configCompile.getUserRegion() || configCompile.getUserRegion().equals("")) {
|
||||
return "id为" + compileId + "的编译配置中userRegion不能为空";
|
||||
}
|
||||
if (null == configCompile.getIsValid()) {
|
||||
return "id为" + compileId + "的编译配置中isValid不能为空";
|
||||
}
|
||||
if (null == configCompile.getGroupNum()) {
|
||||
return "id为" + compileId + "的编译配置中groupNum不能为空";
|
||||
}
|
||||
if (null == configCompile.getFatherCfgId()) {
|
||||
return "id为" + compileId + "的编译配置中fatherCfgId不能为空";
|
||||
}
|
||||
if (null == configCompile.getOpTime()) {
|
||||
return "id为" + compileId + "的编译配置中opTime不能为空";
|
||||
}
|
||||
if (null == configCompile.getActiveSys()) {
|
||||
return "id为" + compileId + "的编译配置中activeSys不能为空";
|
||||
}
|
||||
return "ok";
|
||||
}
|
||||
|
||||
public static String valCompileGroup(ConfigGroupRelation configGroupRelation, Long compileId) {
|
||||
Long groupId = configGroupRelation.getGroupId();
|
||||
if (null == groupId) {
|
||||
return "id为" + compileId + "的编译配置中的配置分组的groupId不能为空";
|
||||
}
|
||||
|
||||
if (null == configGroupRelation.getCompileId()) {
|
||||
return "id为" + compileId + "的编译配置中的配置分组id为" + groupId + "的compileId不能为空";
|
||||
}
|
||||
if (null == configGroupRelation.getIsValid()) {
|
||||
return "id为" + compileId + "的编译配置中的配置分组id为" + groupId + "的isValid不能为空";
|
||||
}
|
||||
|
||||
if (null == configGroupRelation.getOpTime()) {
|
||||
return "id为" + compileId + "的编译配置中的配置分组id为" + groupId + "的opTime不能为空";
|
||||
}
|
||||
return "ok";
|
||||
}
|
||||
|
||||
public static String valIpRegion(IpRegion ipRegion, Long compileId) {
|
||||
|
||||
Long regionId = ipRegion.getRegionId();
|
||||
if (null == regionId) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置的regionId不能为空";
|
||||
}
|
||||
if (null == ipRegion.getGroupId()) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的groupId不能为空";
|
||||
}
|
||||
if (null == ipRegion.getAddrType()) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的addrType不能为空";
|
||||
}
|
||||
if (null == ipRegion.getSrcIp() || ipRegion.getSrcIp().equals("")) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的srcIp不能为空";
|
||||
}
|
||||
|
||||
if (null == ipRegion.getMaskSrcIp() || ipRegion.getMaskSrcIp().equals("")) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的maskSrcIp不能为空";
|
||||
}
|
||||
if (null == ipRegion.getSrcPort() || ipRegion.getSrcPort().equals("")) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的srcPort不能为空";
|
||||
}
|
||||
if (null == ipRegion.getMaskSrcPort() || ipRegion.getMaskSrcPort().equals("")) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的maskSrcPort不能为空";
|
||||
}
|
||||
if (null == ipRegion.getDstIp() || ipRegion.getDstIp().equals("")) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的dstIp不能为空";
|
||||
}
|
||||
if (null == ipRegion.getMaskDstIp() || ipRegion.getMaskDstIp().equals("")) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的maskDstIp不能为空";
|
||||
}
|
||||
if (null == ipRegion.getDstPort() || ipRegion.getDstPort().equals("")) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的dstPort不能为空";
|
||||
}
|
||||
if (null == ipRegion.getMaskDstPort() || ipRegion.getMaskDstPort().equals("")) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的maskDstPort不能为空";
|
||||
}
|
||||
if (null == ipRegion.getProtocol()) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的protocol不能为空";
|
||||
}
|
||||
if (null == ipRegion.getDirection()) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的direction不能为空";
|
||||
}
|
||||
if (null == ipRegion.getIsValid()) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的isValid不能为空";
|
||||
}
|
||||
return "ok";
|
||||
}
|
||||
|
||||
public static String valNumRegion(NumRegion numRegion, Long compileId) {
|
||||
Long regionId = numRegion.getRegionId();
|
||||
if (null == regionId) {
|
||||
return "id为" + compileId + "的编译配置中的数值类域配置的regionId不能为空";
|
||||
}
|
||||
if (null == numRegion.getGroupId()) {
|
||||
return "id为" + compileId + "的编译配置中的数值类域配置id为" + regionId + "的groupId不能为空";
|
||||
}
|
||||
if (null == numRegion.getLowBoundary()) {
|
||||
return "id为" + compileId + "的编译配置中的数值类域配置id为" + regionId + "的lowBoundary不能为空";
|
||||
}
|
||||
if (null == numRegion.getUpBoundary()) {
|
||||
return "id为" + compileId + "的编译配置中的数值类域配置id为" + regionId + "的upBoundary不能为空";
|
||||
}
|
||||
return "ok";
|
||||
}
|
||||
|
||||
public static String valStrRegion(StrRegion strRegion, Long compileId, boolean isDirtrict) {
|
||||
Long regionId = strRegion.getRegionId();
|
||||
if (null == regionId) {
|
||||
return "id为" + compileId + "的编译配置中的字符串类域配置的regionId不能为空";
|
||||
}
|
||||
if (null == strRegion.getGroupId()) {
|
||||
return "id为" + compileId + "的编译配置中的字符串类域配置id为" + regionId + "的groupId不能为空";
|
||||
}
|
||||
if (isDirtrict && (null == strRegion.getDistrict() || strRegion.getDistrict().equals(""))) {
|
||||
return "id为" + compileId + "的编译配置中的字符串类域配置id为" + regionId + "的district不能为空";
|
||||
}
|
||||
|
||||
if (null == strRegion.getKeywords() || strRegion.getKeywords().equals("")) {
|
||||
return "id为" + compileId + "的编译配置中的字符串类域配置id为" + regionId + "的keywords不能为空";
|
||||
}
|
||||
|
||||
if (null == strRegion.getExprType()) {
|
||||
return "id为" + compileId + "的编译配置中的字符串类域配置id为" + regionId + "的exprType不能为空";
|
||||
}
|
||||
|
||||
if (null == strRegion.getMatchMethod()) {
|
||||
return "id为" + compileId + "的编译配置中的字符串类域配置id为" + regionId + "的matchMethod不能为空";
|
||||
}
|
||||
if (null == strRegion.getIsHexbin()) {
|
||||
return "id为" + compileId + "的编译配置中的字符串类域配置id为" + regionId + "的isHexbin不能为空";
|
||||
}
|
||||
return "ok";
|
||||
}
|
||||
|
||||
public static String serviceIpRegionVal(IpRegion ipRegion, Long compileId) {
|
||||
if (!BasicProvingUtil.isIpOrIpMask(ipRegion.getSrcIp(), ipRegion.getAddrType())) {
|
||||
return "编译配置id为" + compileId + "的配置中ipRegionList中regionId为" + ipRegion.getRegionId()
|
||||
+ "的域配置srcIp的格式不正确或与addrType不一致";
|
||||
}
|
||||
if (!BasicProvingUtil.isIpOrIpMask(ipRegion.getMaskSrcIp(), ipRegion.getAddrType())) {
|
||||
return "编译配置id为" + compileId + "的配置中ipRegionList中regionId为" + ipRegion.getRegionId()
|
||||
+ "的域配置maskSrcIp的格式不正确或与addrType不一致";
|
||||
}
|
||||
if (!BasicProvingUtil.isIpOrIpMask(ipRegion.getDstIp(), ipRegion.getAddrType())) {
|
||||
return "编译配置id为" + compileId + "的配置中ipRegionList中regionId为" + ipRegion.getRegionId()
|
||||
+ "的域配置dstIp的格式不正确或与addrType不一致";
|
||||
}
|
||||
if (!BasicProvingUtil.isIpOrIpMask(ipRegion.getMaskDstIp(), ipRegion.getAddrType())) {
|
||||
return "编译配置id为" + compileId + "的配置中ipRegionList中regionId为" + ipRegion.getRegionId()
|
||||
+ "的域配置maskDstIp的格式不正确或与addrType不一致";
|
||||
}
|
||||
|
||||
if (!BasicProvingUtil.isPortOrPortMask(ipRegion.getSrcPort())) {
|
||||
return "编译配置id为" + compileId + "的配置中ipRegionList中regionId为" + ipRegion.getRegionId() + "的域配置srcPort的格式不正确";
|
||||
}
|
||||
// 端口掩码目前先不做0-65535校验,仅做是否是数字校验
|
||||
// if (BasicProvingUtil.isPortOrPortMask(ipRegion.getMaskSrcPort())) {
|
||||
if (!BasicProvingUtil.isIntType(ipRegion.getMaskSrcPort())) {
|
||||
return "编译配置id为" + compileId + "的配置中ipRegionList中regionId为" + ipRegion.getRegionId()
|
||||
+ "的域配置maskSrcPort的格式不正确";
|
||||
}
|
||||
if (!BasicProvingUtil.isPortOrPortMask(ipRegion.getDstPort())) {
|
||||
return "编译配置id为" + compileId + "的配置中ipRegionList中regionId为" + ipRegion.getRegionId() + "的域配置dstPort的格式不正确";
|
||||
}
|
||||
// 端口掩码目前先不做0-65535校验,仅做是否是数字校验
|
||||
// if (BasicProvingUtil.isPortOrPortMask(ipRegion.getMaskDstPort())) {
|
||||
if (!BasicProvingUtil.isIntType(ipRegion.getMaskDstPort())) {
|
||||
return "编译配置id为" + compileId + "的配置中ipRegionList中regionId为" + ipRegion.getRegionId()
|
||||
+ "的域配置maskDstPort的格式不正确";
|
||||
}
|
||||
// if (null == ipRegion.getDirection() || (ipRegion.getDirection() != 1
|
||||
// && ipRegion.getDirection() != 0)) {
|
||||
// return "编译配置id为" + compileId + "的配置中ipRegionList中regionId为" +
|
||||
// ipRegion.getRegionId()
|
||||
// + "的域配置direction的值不正确,只能是0或1";
|
||||
// }
|
||||
return "ok";
|
||||
}
|
||||
|
||||
public static String serviceStrRegionVal(StrRegion strRegion, Long compileId) {
|
||||
String url[] = { "DF_HTTP_URL", "DF_FTP_URL", "DJ_HTTP_URL", "DJ_FTP_URL", "DF_L2TP_URL", "DF_PPTP_URL" };
|
||||
String mail[] = { "DF_MAIL_HDR", "DJ_MAIL_HDR" };
|
||||
String keyWord[] = { "DF_HTTP_REQ_HDR", "DF_HTTP_RES_HDR", "DF_HTTP_REQ_BODY", "DF_HTTP_RES_BODY",
|
||||
"DF_MAIL_BODY", "DF_DNS_REGION", "DF_SSL_REGION", "FX_HTTP_REQ_HDR", "FX_DNS_REGION", "DJ_IP_PKT_BIN",
|
||||
"DJ_HTTP_REQ_HDR", "DJ_HTTP_RES_HDR", "DJ_HTTP_REQ_BODY", "DJ_HTTP_RES_BODY", "DJ_MAIL_BODY",
|
||||
"DJ_DNS_RES_REGION", "DJ_DNS_REQ_REGION", "DJ_SSL_REGION", "FX_HTTP_URL" };
|
||||
|
||||
List<String> urlList = Arrays.asList(url);
|
||||
List<String> mailList = Arrays.asList(mail);
|
||||
List<String> keyWordList = Arrays.asList(keyWord);
|
||||
|
||||
String tableName = strRegion.getTableName();
|
||||
String keywords = strRegion.getKeywords();
|
||||
if (urlList.contains(tableName.toUpperCase())) {
|
||||
List<DataDictionaryValue> dictValue = SystemConfigListener.getDictValue("url");
|
||||
if (null != dictValue && dictValue.size() > 0) {
|
||||
for (DataDictionaryValue dataDictionaryValue : dictValue) {
|
||||
if (dataDictionaryValue.getDataDictValue().equals(keywords)) {
|
||||
return "编译配置id为" + compileId + "的配置中strRegionList中regionId为" + strRegion.getRegionId()
|
||||
+ "的域配置keywords=" + keywords + "被设置为禁配";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} else if (mailList.contains(tableName.toUpperCase())) {
|
||||
List<DataDictionaryValue> dictValue = SystemConfigListener.getDictValue("email");
|
||||
if (null != dictValue && dictValue.size() > 0) {
|
||||
for (DataDictionaryValue dataDictionaryValue : dictValue) {
|
||||
if (dataDictionaryValue.getDataDictValue().equals(keywords)) {
|
||||
return "编译配置id为" + compileId + "的配置中strRegionList中regionId为" + strRegion.getRegionId()
|
||||
+ "的域配置keywords=" + keywords + "被设置为禁配";
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (keyWordList.contains(tableName.toUpperCase())) {
|
||||
List<DataDictionaryValue> dictValue = SystemConfigListener.getDictValue("keywords");
|
||||
if (null != dictValue && dictValue.size() > 0) {
|
||||
String[] split = keywords.split("(?<=[^\\\\])&");
|
||||
for (String str : split) {
|
||||
for (DataDictionaryValue dataDictionaryValue : dictValue) {
|
||||
if (dataDictionaryValue.getDataDictValue().equals(str)) {
|
||||
return "编译配置id为" + compileId + "的配置中strRegionList中regionId为" + strRegion.getRegionId()
|
||||
+ "的域配置keywords=" + str + "被设置为禁配";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return "ok";
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String key = "中\\&国\\&人&河南人&周口人&郸城人";
|
||||
String[] split = key.split("(?<=[^\\\\])&");
|
||||
for (String str : split) {
|
||||
System.out.println(str);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
771
src/main/java/com/nis/util/CompileVal.java
Normal file
771
src/main/java/com/nis/util/CompileVal.java
Normal file
@@ -0,0 +1,771 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import com.nis.domain.restful.ConfigCompile;
|
||||
import com.nis.domain.restful.ConfigGroupRelation;
|
||||
import com.nis.domain.restful.DataDictionaryValue;
|
||||
import com.nis.domain.restful.IpRegion;
|
||||
import com.nis.domain.restful.NumRegion;
|
||||
import com.nis.domain.restful.StrRegion;
|
||||
import com.nis.listener.SystemConfigListener;
|
||||
import com.nis.restful.CompileJudgeCode;
|
||||
import com.nis.web.service.restful.ConfigSourcesService;
|
||||
|
||||
public class CompileVal {
|
||||
|
||||
/**
|
||||
* 判断当前编译配置中的groupNum属性值与配置分组groupList大小是否小于等于8且大于0
|
||||
*
|
||||
* @param configCompile
|
||||
* 编译配置对象
|
||||
* @return GroupNumAndListLtEight GroupNumGtEight GroupListGtEight
|
||||
* GroupNumEQZero GroupListEQZero
|
||||
*
|
||||
*
|
||||
*/
|
||||
@SuppressWarnings("null")
|
||||
public static String groupNumAndListIsOk(ConfigCompile configCompile, boolean isUpdate) {
|
||||
if (null != configCompile) {
|
||||
if (!isUpdate && Constants.BASE_VALIDATE) {
|
||||
String valCompile = valCompile(configCompile);
|
||||
if (!valCompile.equals("ok")) {
|
||||
return valCompile;
|
||||
}
|
||||
}
|
||||
if (null == configCompile.getCompileId()) {
|
||||
return "compileId字段不能为空";
|
||||
}
|
||||
|
||||
if (null == configCompile.getGroupNum()) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.GroupNumIsNull.getErrorReason();
|
||||
}
|
||||
|
||||
if (null != configCompile.getGroupNum() && configCompile.getGroupNum() > 8) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.GroupNumGtEight.getErrorReason();
|
||||
}
|
||||
if (null != configCompile.getGroupNum() && configCompile.getGroupNum() <= 0) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.GroupNumEQZero.getErrorReason();
|
||||
}
|
||||
|
||||
if (null == configCompile.getGroupRelationList()) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.CompileGroupIsNull.getErrorReason();
|
||||
}
|
||||
if (null != configCompile.getGroupRelationList() && configCompile.getGroupRelationList().size() <= 0) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.GroupListEQZero.getErrorReason();
|
||||
}
|
||||
if (null != configCompile.getGroupRelationList() && configCompile.getGroupRelationList().size() > 8) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.GroupListGtEight.getErrorReason();
|
||||
}
|
||||
|
||||
if (configCompile.getGroupRelationList().size() != configCompile.getGroupNum()) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.GroupNumNEQGroupList.getErrorReason();
|
||||
}
|
||||
|
||||
// int sizeCount = 0;
|
||||
// if (configCompile.getIpRegionList() == null && configCompile.getStrRegionList() == null
|
||||
// && configCompile.getNumRegionList() == null) {
|
||||
// return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
// + CompileJudgeCode.CompileNotNull.getErrorReason();
|
||||
// } else {
|
||||
// if (configCompile.getIpRegionList() != null) {
|
||||
// sizeCount += configCompile.getIpRegionList().size();
|
||||
// }
|
||||
// if (configCompile.getStrRegionList() != null) {
|
||||
// sizeCount += configCompile.getStrRegionList().size();
|
||||
// }
|
||||
// if (configCompile.getNumRegionList() != null) {
|
||||
// sizeCount += configCompile.getNumRegionList().size();
|
||||
// }
|
||||
//
|
||||
// if (sizeCount == 0) {
|
||||
// return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
// + CompileJudgeCode.CompileNotNull.getErrorReason();
|
||||
// }
|
||||
// }
|
||||
if (!isUpdate) {
|
||||
if (configCompile.getIsValid() != 1) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置在添加时不能为无效";
|
||||
}
|
||||
} else {
|
||||
if (configCompile.getIsValid() != 0) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置在修改时不能为有效";
|
||||
}
|
||||
}
|
||||
return CompileJudgeCode.GroupNumAndListLtEight.getErrorReason();
|
||||
} else {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的" + CompileJudgeCode.CompileIsNull.getErrorReason();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断编译配置中所有配置分组内域配置个数是否大于0
|
||||
*
|
||||
* @param configCompile
|
||||
* 编译配置对象
|
||||
* @return CompileGroupSizeGtZero CompileGroupSizeEqZero
|
||||
* CompileGroupIdNotExist CompileGroupIdIsRepeat GroupListEQZero
|
||||
*/
|
||||
public static String compileGroupSizeIsGtZero(ConfigCompile configCompile, boolean isUpdate, StringBuffer sb) {
|
||||
Long compileId = configCompile.getCompileId();
|
||||
|
||||
if (!isUpdate && Constants.SERVICE_VALIDATE) {
|
||||
String serviceConfigCompileVal = serviceConfigCompileVal(configCompile);
|
||||
if (!serviceConfigCompileVal.equals("ok")) {
|
||||
return serviceConfigCompileVal;
|
||||
}
|
||||
}
|
||||
|
||||
List<Long> groupList = new ArrayList<Long>();// 配置分组中groupId集合
|
||||
List<ConfigGroupRelation> groupRelationList = configCompile.getGroupRelationList();
|
||||
if (groupRelationList.size() > 0) {
|
||||
for (ConfigGroupRelation configGroupRelation : groupRelationList) {
|
||||
if (!isUpdate && (null == configGroupRelation.getIsValid() || configGroupRelation.getIsValid() != 1)) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置groupRelationList字段中的groupId为"
|
||||
+ configGroupRelation.getGroupId() + "的配置在添加时不能为无效";
|
||||
}
|
||||
if (isUpdate && (null == configGroupRelation.getIsValid() || configGroupRelation.getIsValid() != 0)) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置groupRelationList字段中的groupId为"
|
||||
+ configGroupRelation.getGroupId() + "的配置在修改时不能为有效";
|
||||
}
|
||||
|
||||
if (!isUpdate && Constants.BASE_VALIDATE) {
|
||||
String valCompileGroup = valCompileGroup(configGroupRelation, compileId);
|
||||
if (!valCompileGroup.equals("ok")) {
|
||||
return valCompileGroup;
|
||||
}
|
||||
}
|
||||
|
||||
if (!configGroupRelation.getCompileId().equals(compileId)) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中groupRelationList字段中的groupId为"
|
||||
+ configGroupRelation.getGroupId() + "的配置分组与编译配置id不一致";
|
||||
}
|
||||
if (!groupList.contains(configGroupRelation.getGroupId())) {
|
||||
groupList.add(configGroupRelation.getGroupId());
|
||||
} else {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中groupRelationList存在多个groupId为"
|
||||
+ configGroupRelation.getGroupId() + "的配置分组";
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.GroupListEQZero.getErrorReason();
|
||||
}
|
||||
|
||||
List<Long> regionGroupIdList = new ArrayList<Long>();// 所有域配置中groupId的集合,不重复
|
||||
List<NumRegion> numRegionList = configCompile.getNumRegionList();
|
||||
if (numRegionList == null) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.NumRegionIsNull.getErrorReason();
|
||||
}
|
||||
if (numRegionList.size() > 0) {
|
||||
for (NumRegion numRegion : numRegionList) {
|
||||
// if (configCompile.getIsValid() != 0 &&
|
||||
// !regionGroupIdList.contains(numRegion.getGroupId())) {
|
||||
if (!type2TableNameIsOk(configCompile.getService(), numRegion.getTableName())) {
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置中numRegionList中的regionid为"
|
||||
+ numRegion.getRegionId() + "的域配置tableName与编译配置业务类型不一致";
|
||||
}
|
||||
if (!isUpdate && numRegion.getIsValid() != 1) {
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置中numRegionList中的regionid为"
|
||||
+ numRegion.getRegionId() + "的域配置在添加时不能为无效";
|
||||
}
|
||||
if (isUpdate && numRegion.getIsValid() != 0) {
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置中numRegionList中的regionid为"
|
||||
+ numRegion.getRegionId() + "的域配置在修改时不能为有效";
|
||||
}
|
||||
|
||||
if (groupList.size() > 0 && !groupList.contains(numRegion.getGroupId())) {
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置中numRegionList中的regionid为"
|
||||
+ numRegion.getRegionId() + "的配置的groupid在配置分组关系中不存在";
|
||||
}
|
||||
|
||||
if (!regionGroupIdList.contains(numRegion.getGroupId())) {
|
||||
regionGroupIdList.add(numRegion.getGroupId());
|
||||
}
|
||||
|
||||
if (!isUpdate && Constants.BASE_VALIDATE) {
|
||||
String valNumRegion = valNumRegion(numRegion, compileId);
|
||||
if (!valNumRegion.equals("ok")) {
|
||||
return valNumRegion;
|
||||
}
|
||||
}
|
||||
if (!isUpdate && Constants.SERVICE_VALIDATE) {
|
||||
String serviceNumRegionVal = serviceNumRegionVal(numRegion, compileId);
|
||||
if (!serviceNumRegionVal.equals("ok")) {
|
||||
return serviceNumRegionVal;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<StrRegion> strRegionList = configCompile.getStrRegionList();
|
||||
if (strRegionList == null) {
|
||||
return "编译配置id为" + configCompile.getCompileId() + "的配置中"
|
||||
+ CompileJudgeCode.StrRegionIsNull.getErrorReason();
|
||||
}
|
||||
if (strRegionList != null && strRegionList.size() > 0) {
|
||||
for (StrRegion strRegion : strRegionList) {
|
||||
// if (configCompile.getIsValid() != 0 &&
|
||||
// !regionGroupIdList.contains(strRegion.getGroupId())) {
|
||||
if (!type2TableNameIsOk(configCompile.getService(), strRegion.getTableName())) {
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置中strRegionList中的regionid为"
|
||||
+ strRegion.getRegionId() + "的域配置tableName与编译配置业务类型不一致";
|
||||
}
|
||||
if (!isUpdate && strRegion.getIsValid() != 1) {
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置中strRegionList中的regionid为"
|
||||
+ strRegion.getRegionId() + "的域配置在添加时不能为无效";
|
||||
}
|
||||
if (isUpdate && strRegion.getIsValid() != 0) {
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置中strRegionList中的regionid为"
|
||||
+ strRegion.getRegionId() + "的域配置在修改时不能为有效";
|
||||
}
|
||||
|
||||
if (groupList.size() > 0 && !groupList.contains(strRegion.getGroupId())) {
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置中strRegionList中的regionid为"
|
||||
+ strRegion.getRegionId() + "的配置的groupid在配置分组关系中不存在";
|
||||
}
|
||||
|
||||
if (!regionGroupIdList.contains(strRegion.getGroupId())) {
|
||||
regionGroupIdList.add(strRegion.getGroupId());
|
||||
}
|
||||
|
||||
if (!isUpdate && Constants.BASE_VALIDATE) {
|
||||
String valStrRegion = valStrRegion(strRegion, compileId,
|
||||
ConfigSourcesService.isStrStrongRegion(strRegion.getTableName()));
|
||||
if (!valStrRegion.equals("ok")) {
|
||||
return valStrRegion;
|
||||
}
|
||||
}
|
||||
if (!isUpdate && Constants.SERVICE_VALIDATE) {
|
||||
String serviceStrRegionVal = serviceStrRegionVal(strRegion, compileId,
|
||||
ConfigSourcesService.isStrStrongRegion(strRegion.getTableName()));
|
||||
if (!serviceStrRegionVal.equals("ok")) {
|
||||
return serviceStrRegionVal;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<IpRegion> ipRegionList = configCompile.getIpRegionList();
|
||||
|
||||
if (ipRegionList == null) {
|
||||
return CompileJudgeCode.IpRegionIsNull.getErrorReason();
|
||||
}
|
||||
if (ipRegionList != null && ipRegionList.size() > 0) {
|
||||
for (IpRegion ipRegion : ipRegionList) {
|
||||
// if (configCompile.getIsValid() != 0 &&
|
||||
// !regionGroupIdList.contains(ipRegion.getGroupId())) {
|
||||
if (!type2TableNameIsOk(configCompile.getService(), ipRegion.getTableName())) {
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置中ipRegionList中的regionid为"
|
||||
+ ipRegion.getRegionId() + "的域配置tableName与编译配置业务类型不一致";
|
||||
}
|
||||
|
||||
if (!isUpdate && (null == ipRegion.getIsValid() || ipRegion.getIsValid() != 1)) {
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置中ipRegionList中的regionid为"
|
||||
+ ipRegion.getRegionId() + "的域配置在添加时不能为无效";
|
||||
}
|
||||
if (isUpdate && (null == ipRegion.getIsValid() || ipRegion.getIsValid() != 0)) {
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置中ipRegionList中的regionid为"
|
||||
+ ipRegion.getRegionId() + "的域配置在修改时不能为有效";
|
||||
}
|
||||
|
||||
if (groupList.size() > 0 && !groupList.contains(ipRegion.getGroupId())) {
|
||||
return "配置id为" + configCompile.getCompileId() + "的配置中ipRegionList中的regionid为"
|
||||
+ ipRegion.getRegionId() + "的配置的groupid在配置分组关系中不存在";
|
||||
}
|
||||
if (!regionGroupIdList.contains(ipRegion.getGroupId())) {
|
||||
regionGroupIdList.add(ipRegion.getGroupId());
|
||||
}
|
||||
|
||||
if (!isUpdate && Constants.BASE_VALIDATE) {
|
||||
String valIpRegion = valIpRegion(ipRegion, compileId);
|
||||
if (!valIpRegion.equals("ok")) {
|
||||
return valIpRegion;
|
||||
}
|
||||
}
|
||||
|
||||
if (!isUpdate && Constants.SERVICE_VALIDATE) {
|
||||
String serviceIpRegionVal = serviceIpRegionVal(ipRegion, compileId);
|
||||
if (!serviceIpRegionVal.equals("ok")) {
|
||||
return serviceIpRegionVal;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// if (regionGroupIdList.size() > 0 && groupList.size() > 0 && groupList.size() != regionGroupIdList.size()) {
|
||||
// for (Long groupId : groupList) {
|
||||
// if (!regionGroupIdList.contains(groupId)) {
|
||||
// return "配置id为" + configCompile.getCompileId() + "的配置中配置分组groupid为" + groupId + "的配置在域配置中未被使用";
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// for (Long groupId : regionGroupIdList) {
|
||||
// if (!groupList.contains(groupId)) {
|
||||
// return "配置id为" + configCompile.getCompileId() + "的配置中域配置中的groupid为" + groupId + "的域配置在配置分组关系中不存在";
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// }
|
||||
|
||||
return CompileJudgeCode.CompileGroupSizeGtZero.getErrorReason();
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证业务类型与域配置的表名是否对应
|
||||
*
|
||||
* @param serviceType
|
||||
* @param tableName
|
||||
* @return
|
||||
*/
|
||||
public static boolean type2TableNameIsOk(Long serviceType, String tableName) {
|
||||
if (null != serviceType && null != tableName && !tableName.equals("")) {
|
||||
Map<Integer, Map<String, String>> tableRelation = ConfigSourcesService.getTableRelation();
|
||||
Map<String, String> map = tableRelation.get(serviceType.intValue());
|
||||
if (null != map) {
|
||||
if (map.containsKey(tableName.toUpperCase())) {
|
||||
return true;
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断当前编译配置中的groupNum属性与配置分组groupList大小是否相等且是否均大于0小于等于8, 且每个配置分组中域配置个数大于0
|
||||
*
|
||||
* @param configCompile
|
||||
* @return GroupNumNEQGroupList GroupNumGtEight GroupListGtEight
|
||||
* GroupNumEQZero GroupListEQZero CompileGroupSizeEqZero
|
||||
* CompileGroupIdNotExist CompileGroupIdIsRepeat CompileIsOk
|
||||
* 只有返回CompileIsOk才说明该条配置正常否则该条配置不正常,可根据枚举中成员的注释具体在返回错误信息
|
||||
*/
|
||||
public static String compileIsOk(ConfigCompile configCompile, boolean isUpdate, StringBuffer sb) {
|
||||
|
||||
String msg1 = groupNumAndListIsOk(configCompile, isUpdate);
|
||||
if (msg1 != CompileJudgeCode.GroupNumAndListLtEight.getErrorReason()) {
|
||||
return msg1;
|
||||
}
|
||||
|
||||
String msg2 = compileGroupSizeIsGtZero(configCompile, isUpdate, sb);
|
||||
if (msg2 != CompileJudgeCode.CompileGroupSizeGtZero.getErrorReason()) {
|
||||
return msg2;
|
||||
}
|
||||
String latentMsg = ",数据中可能存在的问题:";
|
||||
if (sb.length() > 0 && !sb.toString().contains(latentMsg)) {
|
||||
latentMsg = latentMsg + sb.toString();
|
||||
sb.setLength(0);
|
||||
sb.append(latentMsg);
|
||||
}
|
||||
return CompileJudgeCode.CompileIsOk.getErrorReason();
|
||||
}
|
||||
|
||||
public static void setSbStr(String str, StringBuffer sb) {
|
||||
if (sb.length() <= 1024) {
|
||||
sb.append(str);
|
||||
}
|
||||
}
|
||||
|
||||
public static String valCompile(ConfigCompile configCompile) {
|
||||
Long compileId = configCompile.getCompileId();
|
||||
if (null == compileId) {
|
||||
return "compileId字段不能为空";
|
||||
}
|
||||
if (null == configCompile.getService()) {
|
||||
return "id为" + compileId + "的编译配置中service不能为空";
|
||||
}
|
||||
|
||||
if (null == configCompile.getAction()) {
|
||||
return "id为" + compileId + "的编译配置中action不能为空";
|
||||
}
|
||||
if (null == configCompile.getDoBlackList()) {
|
||||
return "id为" + compileId + "的编译配置中doBlackList不能为空";
|
||||
}
|
||||
if (null == configCompile.getDoLog()) {
|
||||
return "id为" + compileId + "的编译配置中doLog不能为空";
|
||||
}
|
||||
if (null == configCompile.getEffectiveRange() || configCompile.getEffectiveRange().equals("")) {
|
||||
return "id为" + compileId + "的编译配置中effectiveRange不能为空";
|
||||
}
|
||||
if (null == configCompile.getConfigPercent()) {
|
||||
return "id为" + compileId + "的编译配置中configPercent不能为空";
|
||||
}
|
||||
if (null == configCompile.getConfigOption()) {
|
||||
return "id为" + compileId + "的编译配置中configOption不能为空";
|
||||
}
|
||||
if (null == configCompile.getStartTime()) {
|
||||
return "id为" + compileId + "的编译配置中startTime不能为空";
|
||||
}
|
||||
if (null == configCompile.getEndTime()) {
|
||||
return "id为" + compileId + "的编译配置中endTime不能为空";
|
||||
}
|
||||
if (null == configCompile.getUserRegion() || configCompile.getUserRegion().equals("")) {
|
||||
return "id为" + compileId + "的编译配置中userRegion不能为空";
|
||||
}
|
||||
if (null == configCompile.getIsValid()) {
|
||||
return "id为" + compileId + "的编译配置中isValid不能为空";
|
||||
}
|
||||
if (null == configCompile.getGroupNum()) {
|
||||
return "id为" + compileId + "的编译配置中groupNum不能为空";
|
||||
}
|
||||
if (null == configCompile.getFatherCfgId()) {
|
||||
return "id为" + compileId + "的编译配置中fatherCfgId不能为空";
|
||||
}
|
||||
if (null == configCompile.getOpTime()) {
|
||||
return "id为" + compileId + "的编译配置中opTime不能为空";
|
||||
}
|
||||
if (null == configCompile.getActiveSys()) {
|
||||
return "id为" + compileId + "的编译配置中activeSys不能为空";
|
||||
}
|
||||
return "ok";
|
||||
}
|
||||
|
||||
public static String valCompileGroup(ConfigGroupRelation configGroupRelation, Long compileId) {
|
||||
Long groupId = configGroupRelation.getGroupId();
|
||||
if (null == groupId) {
|
||||
return "id为" + compileId + "的编译配置中的配置分组的groupId不能为空";
|
||||
}
|
||||
|
||||
if (null == configGroupRelation.getCompileId()) {
|
||||
return "id为" + compileId + "的编译配置中的配置分组id为" + groupId + "的配置compileId不能为空";
|
||||
}
|
||||
if (null == configGroupRelation.getIsValid()) {
|
||||
return "id为" + compileId + "的编译配置中的配置分组id为" + groupId + "的配置isValid不能为空";
|
||||
}
|
||||
|
||||
if (null == configGroupRelation.getOpTime()) {
|
||||
return "id为" + compileId + "的编译配置中的配置分组id为" + groupId + "的配置opTime不能为空";
|
||||
}
|
||||
return "ok";
|
||||
}
|
||||
|
||||
public static String valIpRegion(IpRegion ipRegion, Long compileId) {
|
||||
|
||||
Long regionId = ipRegion.getRegionId();
|
||||
if (null == regionId) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置的regionId不能为空";
|
||||
}
|
||||
if (null == ipRegion.getGroupId()) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的配置groupId不能为空";
|
||||
}
|
||||
if (null == ipRegion.getAddrType()) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的配置addrType不能为空";
|
||||
}
|
||||
if (null == ipRegion.getSrcIp() || ipRegion.getSrcIp().equals("")) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的配置srcIp不能为空";
|
||||
}
|
||||
|
||||
if (null == ipRegion.getMaskSrcIp() || ipRegion.getMaskSrcIp().equals("")) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的配置maskSrcIp不能为空";
|
||||
}
|
||||
if (null == ipRegion.getSrcPort() || ipRegion.getSrcPort().equals("")) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的配置srcPort不能为空";
|
||||
}
|
||||
if (null == ipRegion.getMaskSrcPort() || ipRegion.getMaskSrcPort().equals("")) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的配置maskSrcPort不能为空";
|
||||
}
|
||||
if (null == ipRegion.getDstIp() || ipRegion.getDstIp().equals("")) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的配置dstIp不能为空";
|
||||
}
|
||||
if (null == ipRegion.getMaskDstIp() || ipRegion.getMaskDstIp().equals("")) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的配置maskDstIp不能为空";
|
||||
}
|
||||
if (null == ipRegion.getDstPort() || ipRegion.getDstPort().equals("")) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的配置dstPort不能为空";
|
||||
}
|
||||
if (null == ipRegion.getMaskDstPort() || ipRegion.getMaskDstPort().equals("")) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的配置maskDstPort不能为空";
|
||||
}
|
||||
if (null == ipRegion.getProtocol()) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的配置protocol不能为空";
|
||||
}
|
||||
if (null == ipRegion.getDirection()) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的配置direction不能为空";
|
||||
}
|
||||
if (null == ipRegion.getIsValid()) {
|
||||
return "id为" + compileId + "的编译配置中的ip类域配置id为" + regionId + "的配置isValid不能为空";
|
||||
}
|
||||
return "ok";
|
||||
}
|
||||
|
||||
public static String valNumRegion(NumRegion numRegion, Long compileId) {
|
||||
Long regionId = numRegion.getRegionId();
|
||||
if (null == regionId) {
|
||||
return "id为" + compileId + "的编译配置中的数值类域配置的regionId不能为空";
|
||||
}
|
||||
if (null == numRegion.getGroupId()) {
|
||||
return "id为" + compileId + "的编译配置中的数值类域配置id为" + regionId + "的配置groupId不能为空";
|
||||
}
|
||||
if (null == numRegion.getLowBoundary()) {
|
||||
return "id为" + compileId + "的编译配置中的数值类域配置id为" + regionId + "的配置lowBoundary不能为空";
|
||||
}
|
||||
if (null == numRegion.getUpBoundary()) {
|
||||
return "id为" + compileId + "的编译配置中的数值类域配置id为" + regionId + "的配置upBoundary不能为空";
|
||||
}
|
||||
return "ok";
|
||||
}
|
||||
|
||||
public static String valStrRegion(StrRegion strRegion, Long compileId, boolean isDirtrict) {
|
||||
Long regionId = strRegion.getRegionId();
|
||||
if (null == regionId) {
|
||||
return "id为" + compileId + "的编译配置中的字符串类域配置的regionId不能为空";
|
||||
}
|
||||
if (null == strRegion.getGroupId()) {
|
||||
return "id为" + compileId + "的编译配置中的字符串类域配置id为" + regionId + "的配置groupId不能为空";
|
||||
}
|
||||
if (isDirtrict && (null == strRegion.getDistrict() || strRegion.getDistrict().equals(""))) {
|
||||
return "id为" + compileId + "的编译配置中的字符串类域配置id为" + regionId + "的配置district不能为空";
|
||||
}
|
||||
|
||||
if (null == strRegion.getKeywords() || strRegion.getKeywords().equals("")) {
|
||||
return "id为" + compileId + "的编译配置中的字符串类域配置id为" + regionId + "的配置keywords不能为空";
|
||||
}
|
||||
|
||||
if (null == strRegion.getExprType()) {
|
||||
return "id为" + compileId + "的编译配置中的字符串类域配置id为" + regionId + "的配置exprType不能为空";
|
||||
}
|
||||
|
||||
if (null == strRegion.getMatchMethod()) {
|
||||
return "id为" + compileId + "的编译配置中的字符串类域配置id为" + regionId + "的配置matchMethod不能为空";
|
||||
}
|
||||
if (null == strRegion.getIsHexbin()) {
|
||||
return "id为" + compileId + "的编译配置中的字符串类域配置id为" + regionId + "的配置isHexbin不能为空";
|
||||
}
|
||||
return "ok";
|
||||
}
|
||||
|
||||
public static String serviceIpRegionVal(IpRegion ipRegion, Long compileId) {
|
||||
if (!BasicProvingUtil.isIpOrIpMask(ipRegion.getSrcIp(), ipRegion.getAddrType())) {
|
||||
return "编译配置id为" + compileId + "的配置中ipRegionList中regionId为" + ipRegion.getRegionId()
|
||||
+ "的域配置srcIp的格式不正确或与addrType不一致";
|
||||
}
|
||||
if (!BasicProvingUtil.isIpOrIpMask(ipRegion.getMaskSrcIp(), ipRegion.getAddrType())) {
|
||||
return "编译配置id为" + compileId + "的配置中ipRegionList中regionId为" + ipRegion.getRegionId()
|
||||
+ "的域配置maskSrcIp的格式不正确或与addrType不一致";
|
||||
}
|
||||
if (!BasicProvingUtil.isIpOrIpMask(ipRegion.getDstIp(), ipRegion.getAddrType())) {
|
||||
return "编译配置id为" + compileId + "的配置中ipRegionList中regionId为" + ipRegion.getRegionId()
|
||||
+ "的域配置dstIp的格式不正确或与addrType不一致";
|
||||
}
|
||||
if (!BasicProvingUtil.isIpOrIpMask(ipRegion.getMaskDstIp(), ipRegion.getAddrType())) {
|
||||
return "编译配置id为" + compileId + "的配置中ipRegionList中regionId为" + ipRegion.getRegionId()
|
||||
+ "的域配置maskDstIp的格式不正确或与addrType不一致";
|
||||
}
|
||||
|
||||
if (!BasicProvingUtil.isPortOrPortMask(ipRegion.getSrcPort())) {
|
||||
return "编译配置id为" + compileId + "的配置中ipRegionList中regionId为" + ipRegion.getRegionId() + "的域配置srcPort的格式不正确";
|
||||
}
|
||||
|
||||
if (!BasicProvingUtil.isPortOrPortMask(ipRegion.getMaskSrcPort())) {
|
||||
// if (!BasicProvingUtil.isIntType(ipRegion.getMaskSrcPort())) {
|
||||
return "编译配置id为" + compileId + "的配置中ipRegionList中regionId为" + ipRegion.getRegionId()
|
||||
+ "的域配置maskSrcPort的格式不正确";
|
||||
}
|
||||
if (!BasicProvingUtil.isPortOrPortMask(ipRegion.getDstPort())) {
|
||||
return "编译配置id为" + compileId + "的配置中ipRegionList中regionId为" + ipRegion.getRegionId() + "的域配置dstPort的格式不正确";
|
||||
}
|
||||
|
||||
if (!BasicProvingUtil.isPortOrPortMask(ipRegion.getMaskDstPort())) {
|
||||
// if (!BasicProvingUtil.isIntType(ipRegion.getMaskDstPort())) {
|
||||
return "编译配置id为" + compileId + "的配置中ipRegionList中regionId为" + ipRegion.getRegionId()
|
||||
+ "的域配置maskDstPort的格式不正确";
|
||||
}
|
||||
|
||||
if (ipRegion.getSrcIp().equals(ipRegion.getDstIp())) {
|
||||
return "编译配置id为" + compileId + "的配置中ipRegionList中regionId为" + ipRegion.getRegionId()
|
||||
+ "的域配置srcIp和dstIp不能相同";
|
||||
}
|
||||
if (ipRegion.getDirection() != 1 && ipRegion.getDirection() != 0) {
|
||||
return "编译配置id为" + compileId + "的配置中ipRegionList中regionId为" + ipRegion.getRegionId()
|
||||
+ "的域配置direction的值不正确,只能是0或1";
|
||||
}
|
||||
|
||||
if (ipRegion.getTableName().toLowerCase().equals("dj_ip_port")) {
|
||||
if (ipRegion.getProtocol() < 0 || ipRegion.getProtocol() > 255) {
|
||||
return "编译配置id为" + compileId + "的配置中ipRegionList中regionId为" + ipRegion.getRegionId()
|
||||
+ "的域配置tableName为dj_ip_port时,protocol的取值范围只能是0-255";
|
||||
}
|
||||
} else {
|
||||
if (ipRegion.getProtocol() != 0) {
|
||||
return "编译配置id为" + compileId + "的配置中ipRegionList中regionId为" + ipRegion.getRegionId() + "的域配置tableName为"
|
||||
+ ipRegion.getTableName() + "时,protocol的值只能是0";
|
||||
}
|
||||
|
||||
}
|
||||
return "ok";
|
||||
}
|
||||
|
||||
public static String serviceNumRegionVal(NumRegion numRegion, Long compileId) {
|
||||
Long lowBoundary = numRegion.getLowBoundary();
|
||||
Long upBoundary = numRegion.getUpBoundary();
|
||||
if (lowBoundary <= upBoundary) {
|
||||
if (lowBoundary > 4294967295l || lowBoundary < 0l) {
|
||||
return "编译配置id为" + compileId + "的配置中numRegionList中regionId为" + numRegion.getRegionId()
|
||||
+ "的域配置lowBoundary的值不能大于2的32次方减一(4294967295)或者小于0";
|
||||
}
|
||||
if (upBoundary > 4294967295l || upBoundary < 0l) {
|
||||
return "编译配置id为" + compileId + "的配置中numRegionList中regionId为" + numRegion.getRegionId()
|
||||
+ "的域配置upBoundary的值不能大于2的32次方减一(4294967295)或者小于0";
|
||||
}
|
||||
} else {
|
||||
return "编译配置id为" + compileId + "的配置中numRegionList中regionId为" + numRegion.getRegionId()
|
||||
+ "的域配置lowBoundary的值大于upBoundary,应该是小于或等于";
|
||||
}
|
||||
|
||||
return "ok";
|
||||
}
|
||||
|
||||
public static String serviceConfigCompileVal(ConfigCompile configCompile) {
|
||||
Long compileId = configCompile.getCompileId();
|
||||
if (configCompile.getAction() != 1 && configCompile.getAction() != 2 && configCompile.getAction() != 5
|
||||
&& configCompile.getAction() != 6 && configCompile.getAction() != 7) {
|
||||
return "编译配置id为" + compileId + "的配置中action的值只能是1(阻断),2(监测),5(封堵白名单),6(监测白名单),7(封堵监测都白名单)";
|
||||
}
|
||||
if (configCompile.getDoBlackList() != 1) {
|
||||
return "编译配置id为" + compileId + "的配置中doBlackList的值只能是1";
|
||||
}
|
||||
|
||||
if (configCompile.getDoLog() != 0 && configCompile.getDoLog() != 1 && configCompile.getDoLog() != 2) {
|
||||
return "编译配置id为" + compileId + "的配置中doLog的值只能是0(不需要),1(需要),2(只记录结构化日志,不记录非结构化日志)";
|
||||
}
|
||||
|
||||
if (configCompile.getActiveSys() < 1 || configCompile.getActiveSys() > 7) {
|
||||
return "编译配置id为" + compileId + "的配置中activeSys的值范围只能是1-7";
|
||||
}
|
||||
|
||||
if (configCompile.getConfigOption() != 1 && configCompile.getConfigOption() != 2) {
|
||||
return "编译配置id为" + compileId + "的配置中configOption的值只能是1或2";
|
||||
}
|
||||
|
||||
if (configCompile.getFatherCfgId() != 0) {
|
||||
return "编译配置id为" + compileId + "的配置中fatherCfgId的值只能是0";
|
||||
}
|
||||
if (configCompile.getStartTime().getTime() > configCompile.getEndTime().getTime()) {
|
||||
return "编译配置id为" + compileId + "的配置中startTime不能比endTime晚";
|
||||
}
|
||||
return "ok";
|
||||
}
|
||||
|
||||
public static String serviceStrRegionVal(StrRegion strRegion, Long compileId, boolean isDirtrict) {
|
||||
|
||||
Integer exprType = strRegion.getExprType();
|
||||
Integer matchMethod = strRegion.getMatchMethod();
|
||||
Integer isHexbin = strRegion.getIsHexbin();
|
||||
if (exprType != 0 && exprType != 1) {
|
||||
return "编译配置id为" + compileId + "的配置中strRegionList中regionId为" + strRegion.getRegionId()
|
||||
+ "的域配置exprType的值只能是0(无表达式)或者1(与表达式)";
|
||||
}
|
||||
if (matchMethod != 0 && matchMethod != 1 && matchMethod != 2 && matchMethod != 3) {
|
||||
return "编译配置id为" + compileId + "的配置中strRegionList中regionId为" + strRegion.getRegionId()
|
||||
+ "的域配置matchMethod的值只能是0(子串匹配),1(右匹配),2(左匹配),3(完全匹配)";
|
||||
}
|
||||
|
||||
if (isHexbin != 0 && isHexbin != 1 && isHexbin != 2) {
|
||||
return "编译配置id为" + compileId + "的配置中strRegionList中regionId为" + strRegion.getRegionId()
|
||||
+ "的域配置isHexbin的值只能是0(大小写不敏感,且非HEX)或者1(HEX)或者2(大小写敏感,且非HEX)";
|
||||
}
|
||||
// strRegProhibitConfigWord(strRegion,compileId);
|
||||
return "ok";
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 禁配词业务校验
|
||||
*
|
||||
* @param strRegion
|
||||
* @param compileId
|
||||
* @return
|
||||
*/
|
||||
|
||||
public static String strRegProhibitConfigWord(StrRegion strRegion, Long compileId) {
|
||||
String url[] = { "DF_HTTP_URL", "DF_FTP_URL", "DJ_HTTP_URL", "DJ_FTP_URL", "DF_L2TP_URL", "DF_PPTP_URL" };
|
||||
String mail[] = { "DF_MAIL_HDR", "DJ_MAIL_HDR" };
|
||||
String keyWord[] = { "DF_HTTP_REQ_HDR", "DF_HTTP_RES_HDR", "DF_HTTP_REQ_BODY", "DF_HTTP_RES_BODY",
|
||||
"DF_MAIL_BODY", "DF_DNS_REGION", "DF_SSL_REGION", "FX_HTTP_REQ_HDR", "FX_DNS_REGION", "DJ_IP_PKT_BIN",
|
||||
"DJ_HTTP_REQ_HDR", "DJ_HTTP_RES_HDR", "DJ_HTTP_REQ_BODY", "DJ_HTTP_RES_BODY", "DJ_MAIL_BODY",
|
||||
"DJ_DNS_RES_REGION", "DJ_DNS_REQ_REGION", "DJ_SSL_REGION", "FX_HTTP_URL" };
|
||||
|
||||
List<String> urlList = Arrays.asList(url);
|
||||
List<String> mailList = Arrays.asList(mail);
|
||||
List<String> keyWordList = Arrays.asList(keyWord);
|
||||
|
||||
String tableName = strRegion.getTableName();
|
||||
String keywords = strRegion.getKeywords();
|
||||
if (urlList.contains(tableName.toUpperCase())) {
|
||||
List<DataDictionaryValue> dictValue = SystemConfigListener.getDictValue("url");
|
||||
if (null != dictValue && dictValue.size() > 0) {
|
||||
for (DataDictionaryValue dataDictionaryValue : dictValue) {
|
||||
if (dataDictionaryValue.getDataDictValue().equals(keywords)) {
|
||||
return "编译配置id为" + compileId + "的配置中strRegionList中regionId为" + strRegion.getRegionId()
|
||||
+ "的域配置keywords=" + keywords + "被设置为禁配";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} else if (mailList.contains(tableName.toUpperCase())) {
|
||||
List<DataDictionaryValue> dictValue = SystemConfigListener.getDictValue("email");
|
||||
if (null != dictValue && dictValue.size() > 0) {
|
||||
for (DataDictionaryValue dataDictionaryValue : dictValue) {
|
||||
if (dataDictionaryValue.getDataDictValue().equals(keywords)) {
|
||||
return "编译配置id为" + compileId + "的配置中strRegionList中regionId为" + strRegion.getRegionId()
|
||||
+ "的域配置keywords=" + keywords + "被设置为禁配";
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if (keyWordList.contains(tableName.toUpperCase())) {
|
||||
List<DataDictionaryValue> dictValue = SystemConfigListener.getDictValue("keywords");
|
||||
if (null != dictValue && dictValue.size() > 0) {
|
||||
String[] split = keywords.split("(?<=[^\\\\])&");
|
||||
for (String str : split) {
|
||||
for (DataDictionaryValue dataDictionaryValue : dictValue) {
|
||||
if (dataDictionaryValue.getDataDictValue().equals(str)) {
|
||||
return "编译配置id为" + compileId + "的配置中strRegionList中regionId为" + strRegion.getRegionId()
|
||||
+ "的域配置keywords=" + str + "被设置为禁配";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return "ok";
|
||||
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
|
||||
long x = 2;
|
||||
int count = 0;
|
||||
for (int i = 1; i < 32; i++) {
|
||||
count++;
|
||||
x = x * 2;
|
||||
}
|
||||
|
||||
System.out.println(count + " " + x);
|
||||
|
||||
long maxValue = Long.MAX_VALUE;
|
||||
System.out.println(maxValue);
|
||||
|
||||
String key = "中\\&国\\&人&民共和&国中央&中央人民政府";
|
||||
String[] split = key.split("(?<=[^\\\\])&");
|
||||
for (String str : split) {
|
||||
System.out.println(str);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
84
src/main/java/com/nis/util/Configurations.java
Normal file
84
src/main/java/com/nis/util/Configurations.java
Normal file
@@ -0,0 +1,84 @@
|
||||
package com.nis.util;
|
||||
import java.io.File;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
import com.nis.util.StringUtil;
|
||||
|
||||
|
||||
|
||||
|
||||
public final class Configurations {
|
||||
private static Properties prop = new Properties();
|
||||
|
||||
static {
|
||||
try {
|
||||
prop.load(Configurations.class.getResourceAsStream("/nis.properties"));
|
||||
prop.load(Configurations.class.getResourceAsStream("/table.properties"));
|
||||
prop.load(Configurations.class.getResourceAsStream("/matt.properties"));
|
||||
|
||||
} catch (Exception e) {
|
||||
prop = null;
|
||||
System.err.println("未知nis.properties,请确定文件是否存在!");
|
||||
}
|
||||
}
|
||||
|
||||
public static String getStringProperty(String key, String defaultValue) {
|
||||
if (prop==null||StringUtil.isBlank(prop.getProperty(key))) {
|
||||
return defaultValue;
|
||||
}
|
||||
return prop.getProperty(key).trim();
|
||||
}
|
||||
|
||||
public static int getIntProperty(String key, int defaultValue) {
|
||||
if (prop==null||StringUtil.isBlank(prop.getProperty(key))) {
|
||||
return defaultValue;
|
||||
}
|
||||
return Integer.parseInt(prop.getProperty(key).trim());
|
||||
}
|
||||
|
||||
public static long getLongProperty(String key, long defaultValue) {
|
||||
if (prop==null||StringUtil.isBlank(prop.getProperty(key))) {
|
||||
return defaultValue;
|
||||
}
|
||||
return Long.parseLong(prop.getProperty(key).trim());
|
||||
}
|
||||
|
||||
public static boolean getBooleanProperty(String key, boolean defaultValue) {
|
||||
if (prop==null||StringUtil.isBlank(prop.getProperty(key))) {
|
||||
return defaultValue;
|
||||
}
|
||||
return prop.getProperty(key).toLowerCase().trim().equals("true");
|
||||
}
|
||||
|
||||
public static String getFileDirPathProperty(String key,
|
||||
String defaultValue) {
|
||||
if (prop==null||StringUtil.isBlank(prop.getProperty(key))) {
|
||||
return defaultValue;
|
||||
}
|
||||
String path = prop.getProperty(key).trim();
|
||||
File file = new File(path);
|
||||
if (!file.exists()) {
|
||||
file.mkdir();
|
||||
}
|
||||
return file.getAbsolutePath();
|
||||
}
|
||||
|
||||
public static boolean configPropertyIsFound() {
|
||||
if (prop == null) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
public static Map getProp() {
|
||||
return prop;
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
187
src/main/java/com/nis/util/Constants.java
Normal file
187
src/main/java/com/nis/util/Constants.java
Normal file
@@ -0,0 +1,187 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
|
||||
public final class Constants {
|
||||
|
||||
public static final String DEFAULT_CAPTCHA_PARAM = "captcha";
|
||||
public static final String DEFAULT_MOBILE_PARAM = "mobileLogin";
|
||||
public static final String DEFAULT_MESSAGE_PARAM = "message";
|
||||
|
||||
/**
|
||||
* 词典数据key
|
||||
*/
|
||||
public static final String CACHE_DICT_MAP = "dictMap";
|
||||
|
||||
/**
|
||||
* 上传文件基础虚拟路径
|
||||
*/
|
||||
public static final String USERFILES_BASE_URL = "/userfiles/";
|
||||
|
||||
public static final String HASH_ALGORITHM = "SHA-1";
|
||||
public static final int HASH_INTERATIONS = 1024;
|
||||
public static final int SALT_SIZE = 8;
|
||||
|
||||
public static final int LOG_ACCESS_SUCCESS = 1;
|
||||
public static final int LOG_ACCESS_EXCEPTION = 0;
|
||||
/**
|
||||
* 默认未知方法(未添加词典或未识别)操作类型值为:unknown(8000)
|
||||
*/
|
||||
public static final int DEFAULT_METHOD_TYPE = 8000;
|
||||
|
||||
public static final String SYS_BUSINESS_MENU_NAME = "信访管理";
|
||||
|
||||
public static final String LABEL_DEFAULT = "label";
|
||||
public static final String LABEL_SUCCESS = "label label-success";
|
||||
public static final String LABEL_WARNING = "label label-warning";
|
||||
public static final String LABEL_IMPORTANT = "label label-important";
|
||||
public static final String LABEL_INFO = "label label-info";
|
||||
public static final String LABEL_INVERSE = "label label-inverse";
|
||||
/**
|
||||
* 生效系统
|
||||
*/
|
||||
public static final String ACTIVESYS_A = "4";
|
||||
public static final String ACTIVESYS_B = "2";
|
||||
public static final String ACTIVESYS_C = "1";
|
||||
public static final String ACTIVESYS_ALL = "7";
|
||||
//A+B版
|
||||
public static final String ACTIVESYS_AB = "6";
|
||||
/**
|
||||
* 数据库操作
|
||||
*/
|
||||
public static final String INSERT = "I";
|
||||
public static final String UPDATE = "U";
|
||||
public static final String DELETE = "D";
|
||||
/**
|
||||
* 接口的操作行为opAction
|
||||
*/
|
||||
public static final int OPACTION_POST = 1;
|
||||
public static final int OPACTION_PUT = 2;
|
||||
public static final int OPACTION_DELETE = 3;
|
||||
public static final int OPACTION_GET = 4;
|
||||
/**
|
||||
* 是/否
|
||||
*/
|
||||
public static final String YES = "1";
|
||||
public static final String NO = "0";
|
||||
/**
|
||||
* 每页最大显示数
|
||||
*/
|
||||
public static final int MAX_PAGE_SIZE = Configurations.getIntProperty("maxPageSize", 100000);
|
||||
|
||||
/**
|
||||
* 对/错
|
||||
*/
|
||||
public static final String TRUE = "true";
|
||||
public static final String FALSE = "false";
|
||||
/**
|
||||
* 服务器ip
|
||||
*/
|
||||
public static String SERVCER_HOST = null;
|
||||
/**
|
||||
* oracle redis数据 存储时间
|
||||
*/
|
||||
public static final int ORACLE_EXPIRE = Configurations.getIntProperty("oracleExpire", 180);
|
||||
/**
|
||||
* hive redis数据 存储时间
|
||||
*/
|
||||
public static final int HIVE_EXPIRE = Configurations.getIntProperty("hiveExpire", 180);
|
||||
/**
|
||||
* redis开关
|
||||
*/
|
||||
public static final boolean IS_OPEN_REDIS = Configurations.getBooleanProperty("isOpenRedis", false);
|
||||
/**
|
||||
* es开关
|
||||
*/
|
||||
public static final boolean IS_USE_ES = Configurations.getBooleanProperty("isUseES", false);
|
||||
|
||||
/**
|
||||
* 数据中心日志redis开关
|
||||
*/
|
||||
public static final boolean DATACENTER_OPEN_REDIS = Configurations.getBooleanProperty("dataCenterOpenRedis", false);
|
||||
/**
|
||||
* 是否使用use soq_log命令
|
||||
*/
|
||||
// public static final boolean IS_USE_HIVE_DB =
|
||||
// Configurations.getBooleanProperty("isUseHiveDb", true);
|
||||
|
||||
/**
|
||||
* 是否获取数据中心查询记录的总条数
|
||||
*/
|
||||
|
||||
public static final boolean IS_GET_HIVECOUNT = Configurations.getBooleanProperty("isGetHiveCount", true);
|
||||
/**
|
||||
* 是否获取数据中心[神通]查询记录的总条数
|
||||
*/
|
||||
|
||||
public static final boolean IS_SELECT_CLUSTER = Configurations.getBooleanProperty("isSelectCluster", false);
|
||||
|
||||
/**
|
||||
* 神通数据库A的数据最早时间
|
||||
*/
|
||||
public static final Long CLUSTER_A_START_TIME = Configurations.getLongProperty("clusterAStartTime", new Date().getTime());
|
||||
|
||||
/**
|
||||
* 神通数据库B的数据最早时间
|
||||
*/
|
||||
public static final Long CLUSTER_B_START_TIME = Configurations.getLongProperty("clusterBStartTime", new Date().getTime());
|
||||
|
||||
/**
|
||||
* 每次获取数据中心多少条数据,咱们在对获取的数据进行分页处理
|
||||
*/
|
||||
public static final Long EVERY_GETHIVEDATANUM = Configurations.getLongProperty("everyGetHiveDataNum", 10000);
|
||||
|
||||
/**
|
||||
* 是否开启基础校验
|
||||
*/
|
||||
public static final boolean BASE_VALIDATE = Configurations.getBooleanProperty("baseValidate", true);
|
||||
|
||||
public static final Long DATACENTER_TIME = Configurations.getLongProperty("dataCenterTime", 48);
|
||||
|
||||
/**
|
||||
* 是否开启业务校验
|
||||
*/
|
||||
public static final boolean SERVICE_VALIDATE = Configurations.getBooleanProperty("serviceValidate", true);
|
||||
/**
|
||||
* 日志本地存储时间
|
||||
*/
|
||||
public static final Long LOG_LOCAL_TIME = Configurations.getLongProperty("logLocalTime", 48);
|
||||
/**
|
||||
* 实时统计默认时间
|
||||
*/
|
||||
public static final Long REPORT_LOCAL_TIME = Configurations.getLongProperty("reportLocalTime", 1);
|
||||
|
||||
/**
|
||||
* 日志是否从hive中查询
|
||||
*/
|
||||
public static final boolean SEL_FROM_HIVE = Configurations.getBooleanProperty("selFromHive", true);
|
||||
public static final boolean ONLY_SEL_FROM_HIVE = Configurations.getBooleanProperty("onlySelFromHive", true);
|
||||
|
||||
/**
|
||||
* 跨域问题解决,允许跨域的url
|
||||
*/
|
||||
public static final String TARGET_URL = Configurations.getStringProperty("target_url", "*");
|
||||
public static final String ACCESS_CONTROL_MAX_AGE = Configurations.getStringProperty("ACCESS_CONTROL_MAX_AGE",
|
||||
"3600");
|
||||
/**
|
||||
* elasticsearch 检索相关
|
||||
*/
|
||||
public static final String SEARCH_DATEFORMAT = Configurations.getStringProperty("search.dateformat",
|
||||
"yyyy-MM-dd HH:mm:ss");
|
||||
public static final String SEARCH_ES_HOSTANDPORT_A = Configurations.getStringProperty("search.eshostandport_A",
|
||||
null);
|
||||
public static final String SEARCH_ES_HOSTANDPORT_B = Configurations.getStringProperty("search.eshostandport_B",
|
||||
null);
|
||||
public static final String SEARCH_ES_HOSTANDPORT_C = Configurations.getStringProperty("search.eshostandport_C",
|
||||
null);
|
||||
/**
|
||||
* 数据中心A版数据库名称,程序中每次查询时使用的数据库名称 use HIVEADBNAME
|
||||
*/
|
||||
public static final String HIVEADBNAME = Configurations.getStringProperty("jdbc.hive.AName", "xa_dfbhit_hive");
|
||||
/**
|
||||
* 数据中心B版数据库名称,程序中每次查询时使用的数据库名称 use HIVEBDBNAME
|
||||
*/
|
||||
public static final String HIVEBDBNAME = Configurations.getStringProperty("jdbc.hive.BName", "xa_z2_mesalog_hive");
|
||||
|
||||
}
|
||||
257
src/main/java/com/nis/util/Cryptos.java
Normal file
257
src/main/java/com/nis/util/Cryptos.java
Normal file
@@ -0,0 +1,257 @@
|
||||
/**
|
||||
* Copyright (c) 2005-2012 springside.org.cn
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Arrays;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.KeyGenerator;
|
||||
import javax.crypto.Mac;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.IvParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
|
||||
/**
|
||||
* 支持HMAC-SHA1消息签名 及 DES/AES对称加密的工具类.
|
||||
*
|
||||
* 支持Hex与Base64两种编码方式.
|
||||
*
|
||||
* @author calvin
|
||||
*/
|
||||
public class Cryptos {
|
||||
|
||||
private static final String AES = "AES";
|
||||
private static final String AES_CBC = "AES/CBC/PKCS5Padding";
|
||||
private static final String HMACSHA1 = "HmacSHA1";
|
||||
|
||||
private static final String DEFAULT_URL_ENCODING = "UTF-8";
|
||||
private static final int DEFAULT_HMACSHA1_KEYSIZE = 160; //RFC2401
|
||||
private static final int DEFAULT_AES_KEYSIZE = 128;
|
||||
private static final int DEFAULT_IVSIZE = 16;
|
||||
|
||||
private static final byte[] DEFAULT_KEY = new byte[]{-97,88,-94,9,70,-76,126,25,0,3,-20,113,108,28,69,125};
|
||||
|
||||
private static SecureRandom random = new SecureRandom();
|
||||
|
||||
//-- HMAC-SHA1 funciton --//
|
||||
/**
|
||||
* 使用HMAC-SHA1进行消息签名, 返回字节数组,长度为20字节.
|
||||
*
|
||||
* @param input 原始输入字符数组
|
||||
* @param key HMAC-SHA1密钥
|
||||
*/
|
||||
public static byte[] hmacSha1(byte[] input, byte[] key) {
|
||||
try {
|
||||
SecretKey secretKey = new SecretKeySpec(key, HMACSHA1);
|
||||
Mac mac = Mac.getInstance(HMACSHA1);
|
||||
mac.init(secretKey);
|
||||
return mac.doFinal(input);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw Exceptions.unchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 校验HMAC-SHA1签名是否正确.
|
||||
*
|
||||
* @param expected 已存在的签名
|
||||
* @param input 原始输入字符串
|
||||
* @param key 密钥
|
||||
*/
|
||||
public static boolean isMacValid(byte[] expected, byte[] input, byte[] key) {
|
||||
byte[] actual = hmacSha1(input, key);
|
||||
return Arrays.equals(expected, actual);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成HMAC-SHA1密钥,返回字节数组,长度为160位(20字节).
|
||||
* HMAC-SHA1算法对密钥无特殊要求, RFC2401建议最少长度为160位(20字节).
|
||||
*/
|
||||
public static byte[] generateHmacSha1Key() {
|
||||
try {
|
||||
KeyGenerator keyGenerator = KeyGenerator.getInstance(HMACSHA1);
|
||||
keyGenerator.init(DEFAULT_HMACSHA1_KEYSIZE);
|
||||
SecretKey secretKey = keyGenerator.generateKey();
|
||||
return secretKey.getEncoded();
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw Exceptions.unchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
//-- AES funciton --//
|
||||
|
||||
/**
|
||||
* 使用AES加密原始字符串.
|
||||
*
|
||||
* @param input 原始输入字符数组
|
||||
*/
|
||||
public static String aesEncrypt(String input) {
|
||||
try {
|
||||
return Encodes.encodeHex(aesEncrypt(input.getBytes(DEFAULT_URL_ENCODING), DEFAULT_KEY));
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用AES加密原始字符串.
|
||||
*
|
||||
* @param input 原始输入字符数组
|
||||
* @param key 符合AES要求的密钥
|
||||
*/
|
||||
public static String aesEncrypt(String input, String key) {
|
||||
try {
|
||||
return Encodes.encodeHex(aesEncrypt(input.getBytes(DEFAULT_URL_ENCODING), Encodes.decodeHex(key)));
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用AES加密原始字符串.
|
||||
*
|
||||
* @param input 原始输入字符数组
|
||||
* @param key 符合AES要求的密钥
|
||||
*/
|
||||
public static byte[] aesEncrypt(byte[] input, byte[] key) {
|
||||
return aes(input, key, Cipher.ENCRYPT_MODE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用AES加密原始字符串.
|
||||
*
|
||||
* @param input 原始输入字符数组
|
||||
* @param key 符合AES要求的密钥
|
||||
* @param iv 初始向量
|
||||
*/
|
||||
public static byte[] aesEncrypt(byte[] input, byte[] key, byte[] iv) {
|
||||
return aes(input, key, iv, Cipher.ENCRYPT_MODE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用AES解密字符串, 返回原始字符串.
|
||||
*
|
||||
* @param input Hex编码的加密字符串
|
||||
*/
|
||||
public static String aesDecrypt(String input) {
|
||||
try {
|
||||
return new String(aesDecrypt(Encodes.decodeHex(input), DEFAULT_KEY), DEFAULT_URL_ENCODING);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用AES解密字符串, 返回原始字符串.
|
||||
*
|
||||
* @param input Hex编码的加密字符串
|
||||
* @param key 符合AES要求的密钥
|
||||
*/
|
||||
public static String aesDecrypt(String input, String key) {
|
||||
try {
|
||||
return new String(aesDecrypt(Encodes.decodeHex(input), Encodes.decodeHex(key)), DEFAULT_URL_ENCODING);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用AES解密字符串, 返回原始字符串.
|
||||
*
|
||||
* @param input Hex编码的加密字符串
|
||||
* @param key 符合AES要求的密钥
|
||||
*/
|
||||
public static byte[] aesDecrypt(byte[] input, byte[] key) {
|
||||
return aes(input, key, Cipher.DECRYPT_MODE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用AES解密字符串, 返回原始字符串.
|
||||
*
|
||||
* @param input Hex编码的加密字符串
|
||||
* @param key 符合AES要求的密钥
|
||||
* @param iv 初始向量
|
||||
*/
|
||||
public static byte[] aesDecrypt(byte[] input, byte[] key, byte[] iv) {
|
||||
return aes(input, key, iv, Cipher.DECRYPT_MODE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用AES加密或解密无编码的原始字节数组, 返回无编码的字节数组结果.
|
||||
*
|
||||
* @param input 原始字节数组
|
||||
* @param key 符合AES要求的密钥
|
||||
* @param mode Cipher.ENCRYPT_MODE 或 Cipher.DECRYPT_MODE
|
||||
*/
|
||||
private static byte[] aes(byte[] input, byte[] key, int mode) {
|
||||
try {
|
||||
SecretKey secretKey = new SecretKeySpec(key, AES);
|
||||
Cipher cipher = Cipher.getInstance(AES);
|
||||
cipher.init(mode, secretKey);
|
||||
return cipher.doFinal(input);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw Exceptions.unchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 使用AES加密或解密无编码的原始字节数组, 返回无编码的字节数组结果.
|
||||
*
|
||||
* @param input 原始字节数组
|
||||
* @param key 符合AES要求的密钥
|
||||
* @param iv 初始向量
|
||||
* @param mode Cipher.ENCRYPT_MODE 或 Cipher.DECRYPT_MODE
|
||||
*/
|
||||
private static byte[] aes(byte[] input, byte[] key, byte[] iv, int mode) {
|
||||
try {
|
||||
SecretKey secretKey = new SecretKeySpec(key, AES);
|
||||
IvParameterSpec ivSpec = new IvParameterSpec(iv);
|
||||
Cipher cipher = Cipher.getInstance(AES_CBC);
|
||||
cipher.init(mode, secretKey, ivSpec);
|
||||
return cipher.doFinal(input);
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw Exceptions.unchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成AES密钥,返回字节数组, 默认长度为128位(16字节).
|
||||
*/
|
||||
public static String generateAesKeyString() {
|
||||
return Encodes.encodeHex(generateAesKey(DEFAULT_AES_KEYSIZE));
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成AES密钥,返回字节数组, 默认长度为128位(16字节).
|
||||
*/
|
||||
public static byte[] generateAesKey() {
|
||||
return generateAesKey(DEFAULT_AES_KEYSIZE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成AES密钥,可选长度为128,192,256位.
|
||||
*/
|
||||
public static byte[] generateAesKey(int keysize) {
|
||||
try {
|
||||
KeyGenerator keyGenerator = KeyGenerator.getInstance(AES);
|
||||
keyGenerator.init(keysize);
|
||||
SecretKey secretKey = keyGenerator.generateKey();
|
||||
return secretKey.getEncoded();
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw Exceptions.unchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成随机向量,默认大小为cipher.getBlockSize(), 16字节.
|
||||
*/
|
||||
public static byte[] generateIV() {
|
||||
byte[] bytes = new byte[DEFAULT_IVSIZE];
|
||||
random.nextBytes(bytes);
|
||||
return bytes;
|
||||
}
|
||||
}
|
||||
260
src/main/java/com/nis/util/DateUtils.java
Normal file
260
src/main/java/com/nis/util/DateUtils.java
Normal file
@@ -0,0 +1,260 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Calendar;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.lang3.time.DateFormatUtils;
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
/**
|
||||
* 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
|
||||
* @author ThinkGem
|
||||
* @version 2014-4-15
|
||||
*/
|
||||
public class DateUtils extends org.apache.commons.lang3.time.DateUtils {
|
||||
public static final Logger logger = Logger.getLogger(DateUtils.class);
|
||||
private static String[] parsePatterns = {
|
||||
"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
|
||||
"yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
|
||||
"yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
|
||||
|
||||
/**
|
||||
* 得到当前日期字符串 格式(yyyy-MM-dd)
|
||||
*/
|
||||
public static String getDate() {
|
||||
return getDate("yyyy-MM-dd");
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
|
||||
*/
|
||||
public static String getDate(String pattern) {
|
||||
return DateFormatUtils.format(new Date(), pattern);
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
|
||||
*/
|
||||
public static String formatDate(Date date, Object... pattern) {
|
||||
String formatDate = null;
|
||||
if (pattern != null && pattern.length > 0) {
|
||||
formatDate = DateFormatUtils.format(date, pattern[0].toString());
|
||||
} else {
|
||||
formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
|
||||
}
|
||||
return formatDate;
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss)
|
||||
*/
|
||||
public static String formatDateTime(Date date) {
|
||||
return formatDate(date, "yyyy-MM-dd HH:mm:ss");
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到当前时间字符串 格式(HH:mm:ss)
|
||||
*/
|
||||
public static String getTime() {
|
||||
return formatDate(new Date(), "HH:mm:ss");
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss)
|
||||
*/
|
||||
public static String getDateTime() {
|
||||
return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到当前年份字符串 格式(yyyy)
|
||||
*/
|
||||
public static String getYear() {
|
||||
return formatDate(new Date(), "yyyy");
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到当前月份字符串 格式(MM)
|
||||
*/
|
||||
public static String getMonth() {
|
||||
return formatDate(new Date(), "MM");
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到当天字符串 格式(dd)
|
||||
*/
|
||||
public static String getDay() {
|
||||
return formatDate(new Date(), "dd");
|
||||
}
|
||||
|
||||
/**
|
||||
* 得到当前星期字符串 格式(E)星期几
|
||||
*/
|
||||
public static String getWeek() {
|
||||
return formatDate(new Date(), "E");
|
||||
}
|
||||
|
||||
/**
|
||||
* 日期型字符串转化为日期 格式
|
||||
* { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
|
||||
* "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm",
|
||||
* "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm" }
|
||||
*/
|
||||
public static Date parseDate(Object str) {
|
||||
if (str == null){
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return parseDate(str.toString(), parsePatterns);
|
||||
} catch (ParseException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取过去的天数
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public static long pastDays(Date date) {
|
||||
long t = new Date().getTime()-date.getTime();
|
||||
return t/(24*60*60*1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取过去的小时
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public static long pastHour(Date date) {
|
||||
long t = new Date().getTime()-date.getTime();
|
||||
return t/(60*60*1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取过去的分钟
|
||||
* @param date
|
||||
* @return
|
||||
*/
|
||||
public static long pastMinutes(Date date) {
|
||||
long t = new Date().getTime()-date.getTime();
|
||||
return t/(60*1000);
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为时间(天,时:分:秒.毫秒)
|
||||
* @param timeMillis
|
||||
* @return
|
||||
*/
|
||||
public static String formatDateTime(long timeMillis){
|
||||
long day = timeMillis/(24*60*60*1000);
|
||||
long hour = (timeMillis/(60*60*1000)-day*24);
|
||||
long min = ((timeMillis/(60*1000))-day*24*60-hour*60);
|
||||
long s = (timeMillis/1000-day*24*60*60-hour*60*60-min*60);
|
||||
long sss = (timeMillis-day*24*60*60*1000-hour*60*60*1000-min*60*1000-s*1000);
|
||||
return (day>0?day+",":"")+hour+":"+min+":"+s+"."+sss;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取两个日期之间的天数
|
||||
*
|
||||
* @param before
|
||||
* @param after
|
||||
* @return
|
||||
*/
|
||||
public static double getDistanceOfTwoDate(Date before, Date after) {
|
||||
long beforeTime = before.getTime();
|
||||
long afterTime = after.getTime();
|
||||
return (afterTime - beforeTime) / (1000 * 60 * 60 * 24);
|
||||
}
|
||||
/**
|
||||
*
|
||||
*
|
||||
* @Title: getLocalTime
|
||||
* @Description: (各种业务查询的时间条件默认值)
|
||||
* @param @param startTime
|
||||
* @param @param endTime
|
||||
* @param @param 本地存储时间长度(小时)
|
||||
* @param @return
|
||||
* @return Map 返回类型
|
||||
* @author (DDM)
|
||||
* @version V1.0
|
||||
*/
|
||||
public static Map<String, String> getLocalTime(String startTime,String endTime,Long localLen,String type)throws Exception {
|
||||
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
SimpleDateFormat sdf2=new SimpleDateFormat("yyyy-MM-dd");
|
||||
Map<String, String> timeMap=new HashMap<String, String>();
|
||||
Date date=new Date();
|
||||
//日报表默认查询前一天的数据
|
||||
if("daily".equals(type) && startTime == null && endTime == null){
|
||||
Calendar cal=Calendar.getInstance();
|
||||
cal.add(Calendar.DAY_OF_YEAR, -1);
|
||||
cal.set(Calendar.HOUR_OF_DAY, 0);
|
||||
cal.set(Calendar.MINUTE, 0);
|
||||
cal.set(Calendar.SECOND, 0);
|
||||
timeMap.put("startTime", sdf.format(cal.getTime()));
|
||||
timeMap.put("endTime", sdf.format(sdf.parse(sdf2.format(cal.getTime())+" 23:59:59")));
|
||||
logger.info("日报默认开始时间条件:"+sdf.format(cal.getTime()));
|
||||
logger.info("日报默认结束时间条件:"+sdf.format(sdf.parse(sdf2.format(cal.getTime())+" 23:59:59")));
|
||||
return timeMap;
|
||||
}
|
||||
//月报表默认查询前一天的数据
|
||||
if("month".equals(type) && startTime == null && endTime == null){
|
||||
Calendar cal=Calendar.getInstance();
|
||||
cal.add(Calendar.MONTH, date.getMonth()-2);
|
||||
cal.set(Calendar.DAY_OF_MONTH, 1);
|
||||
cal.set(Calendar.HOUR_OF_DAY, 0);
|
||||
cal.set(Calendar.MINUTE, 0);
|
||||
cal.set(Calendar.SECOND, 0);
|
||||
timeMap.put("startTime", sdf.format(cal.getTime()));
|
||||
timeMap.put("endTime", sdf.format(date));
|
||||
logger.info("月报默认开始时间条件:"+sdf.format(cal.getTime()));
|
||||
logger.info("月报默认结束时间条件:"+sdf.format(date));
|
||||
return timeMap;
|
||||
}
|
||||
|
||||
if(startTime == null && endTime == null && localLen != null){
|
||||
Calendar cal=Calendar.getInstance();
|
||||
cal.add(Calendar.HOUR, -localLen.intValue());
|
||||
timeMap.put("startTime", sdf.format(cal.getTime()));
|
||||
timeMap.put("endTime", sdf.format(date));
|
||||
logger.info("默认开始时间条件:"+sdf.format(cal.getTime()));
|
||||
logger.info("默认结束时间条件:"+sdf.format(date));
|
||||
return timeMap;
|
||||
}else {
|
||||
timeMap.put("startTime", startTime);
|
||||
timeMap.put("endTime", endTime);
|
||||
logger.info("开始时间条件:"+startTime);
|
||||
logger.info("结束时间条件:"+endTime);
|
||||
return timeMap;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param args
|
||||
* @throws ParseException
|
||||
*/
|
||||
public static void main(String[] args) throws ParseException {
|
||||
// System.out.println(formatDate(parseDate("2010/3/6")));
|
||||
// System.out.println(getDate("yyyy年MM月dd日 E"));
|
||||
// long time = new Date().getTime()-parseDate("2012-11-19").getTime();
|
||||
// System.out.println(time/(24*60*60*1000));
|
||||
Date date=new Date();
|
||||
Calendar cal=Calendar.getInstance();
|
||||
cal.add(Calendar.MONTH, date.getMonth()-2);
|
||||
cal.set(Calendar.DAY_OF_MONTH, 1);
|
||||
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
|
||||
//timeMap.put("startTime", sdf.format(cal2.getTime()));
|
||||
//timeMap.put("endTime", sdf.format(cal.getTime()));
|
||||
logger.info("月报默认开始时间条件:"+sdf.format(cal.getTime()));
|
||||
}
|
||||
}
|
||||
146
src/main/java/com/nis/util/DictUtils.java
Normal file
146
src/main/java/com/nis/util/DictUtils.java
Normal file
@@ -0,0 +1,146 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.nis.domain.SysDataDictionaryItem;
|
||||
import com.nis.domain.SysDataDictionaryName;
|
||||
import com.nis.web.dao.SysDictDao;
|
||||
import com.nis.web.service.SpringContextHolder;
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 系统数据字典工具类
|
||||
* @author Administrator
|
||||
*
|
||||
*/
|
||||
public class DictUtils {
|
||||
|
||||
private final static SysDictDao dictDao = SpringContextHolder.getBean(SysDictDao.class);
|
||||
|
||||
|
||||
public static Map<String, List<SysDataDictionaryItem>> getDictData() {
|
||||
|
||||
Map<String, List<SysDataDictionaryItem>> dictMap = (Map<String, List<SysDataDictionaryItem>>)CacheUtils.get(Constants.CACHE_DICT_MAP);
|
||||
|
||||
if (StringUtil.isEmpty(dictMap)) {
|
||||
dictMap = Maps.newHashMap();
|
||||
List<SysDataDictionaryName> dicList = dictDao.findAllList(new SysDataDictionaryName());
|
||||
for (SysDataDictionaryName dict : dicList) {
|
||||
dictMap.put(dict.getMark(), dict.getDictItemList());
|
||||
}
|
||||
CacheUtils.put(Constants.CACHE_DICT_MAP, dictMap);
|
||||
}
|
||||
|
||||
return dictMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取词典对应key的所有词条,code:value
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static Map<String,String> getDictOption(String key) {
|
||||
List<SysDataDictionaryItem> itemList = getDictData().get(key);
|
||||
Map<String, String> itemMap = Maps.newHashMap();
|
||||
for (SysDataDictionaryItem item : itemList) {
|
||||
itemMap.put(item.getItemCode(), item.getItemValue());
|
||||
}
|
||||
|
||||
return itemMap;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取词典对应key的所有词条,value:code
|
||||
* @param key
|
||||
* @return
|
||||
*/
|
||||
public static Map<String,String> getDictOptionInReversion(String key) {
|
||||
List<SysDataDictionaryItem> itemList = getDictData().get(key);
|
||||
Map<String, String> itemMap = Maps.newHashMap();
|
||||
for (SysDataDictionaryItem item : itemList) {
|
||||
itemMap.put(item.getItemValue(), item.getItemCode());
|
||||
}
|
||||
|
||||
return itemMap;
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static List<SysDataDictionaryItem> getDictList(String key){
|
||||
List<SysDataDictionaryItem> itemList = getDictData().get(key);
|
||||
if (StringUtil.isEmpty(itemList)) {
|
||||
itemList = Lists.newArrayList();
|
||||
}
|
||||
return itemList;
|
||||
}
|
||||
|
||||
public static String getDictLabels(String dictKey, String itemCodes, String defaultValue){
|
||||
|
||||
Map<String, String> itemMap = getDictOption(dictKey);
|
||||
|
||||
if (!StringUtil.isEmpty(itemMap)) {
|
||||
List<String> valueList = Lists.newArrayList();
|
||||
for (String itemCode : StringUtils.split(itemCodes, ",")){
|
||||
valueList.add(itemMap.get(itemCode));
|
||||
}
|
||||
return StringUtils.join(valueList, ",");
|
||||
|
||||
}
|
||||
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取字典词条标签
|
||||
* @param value
|
||||
* @param type
|
||||
* @param defaultValue
|
||||
* @return
|
||||
*/
|
||||
public static String getDictLabel(String dictKey, String itemCode, String defaultValue){
|
||||
String itemLabel = getDictOption(dictKey).get(itemCode);
|
||||
|
||||
return StringUtil.isBlank(itemLabel) ? defaultValue : itemLabel;
|
||||
}
|
||||
|
||||
public static String getDictLabel(String dictKey, String itemCode){
|
||||
|
||||
return getDictLabel(dictKey, itemCode, "默认");
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static String getDictCode(String dictKey, String itemValue, String defaultValue){
|
||||
String itemCode = getDictOptionInReversion(dictKey).get(itemValue);
|
||||
|
||||
return StringUtil.isBlank(itemCode) ? defaultValue : itemCode;
|
||||
}
|
||||
|
||||
|
||||
public static String getDictCode(String dictKey, String itemValue){
|
||||
return getDictCode(dictKey, itemValue, "默认");
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 返回字典列表(JSON)
|
||||
* @param type
|
||||
* @return
|
||||
*/
|
||||
public static String getDictListJson(String key){
|
||||
return JsonMapper.toJsonString(getDictList(key));
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
}
|
||||
122
src/main/java/com/nis/util/Digests.java
Normal file
122
src/main/java/com/nis/util/Digests.java
Normal file
@@ -0,0 +1,122 @@
|
||||
/**
|
||||
* Copyright (c) 2005-2012 springside.org.cn
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.security.GeneralSecurityException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
|
||||
import org.apache.commons.lang3.Validate;
|
||||
|
||||
|
||||
/**
|
||||
* 支持SHA-1/MD5消息摘要的工具类.
|
||||
*
|
||||
* 返回ByteSource,可进一步被编码为Hex, Base64或UrlSafeBase64
|
||||
*
|
||||
* @author calvin
|
||||
*/
|
||||
public class Digests {
|
||||
|
||||
private static final String SHA1 = "SHA-1";
|
||||
private static final String MD5 = "MD5";
|
||||
|
||||
private static SecureRandom random = new SecureRandom();
|
||||
|
||||
/**
|
||||
* 对输入字符串进行md5散列.
|
||||
*/
|
||||
public static byte[] md5(byte[] input) {
|
||||
return digest(input, MD5, null, 1);
|
||||
}
|
||||
public static byte[] md5(byte[] input, int iterations) {
|
||||
return digest(input, MD5, null, iterations);
|
||||
}
|
||||
|
||||
/**
|
||||
* 对输入字符串进行sha1散列.
|
||||
*/
|
||||
public static byte[] sha1(byte[] input) {
|
||||
return digest(input, SHA1, null, 1);
|
||||
}
|
||||
|
||||
public static byte[] sha1(byte[] input, byte[] salt) {
|
||||
return digest(input, SHA1, salt, 1);
|
||||
}
|
||||
|
||||
public static byte[] sha1(byte[] input, byte[] salt, int iterations) {
|
||||
return digest(input, SHA1, salt, iterations);
|
||||
}
|
||||
|
||||
/**
|
||||
* 对字符串进行散列, 支持md5与sha1算法.
|
||||
*/
|
||||
private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) {
|
||||
try {
|
||||
MessageDigest digest = MessageDigest.getInstance(algorithm);
|
||||
|
||||
if (salt != null) {
|
||||
digest.update(salt);
|
||||
}
|
||||
|
||||
byte[] result = digest.digest(input);
|
||||
|
||||
for (int i = 1; i < iterations; i++) {
|
||||
digest.reset();
|
||||
result = digest.digest(result);
|
||||
}
|
||||
return result;
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw Exceptions.unchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成随机的Byte[]作为salt.
|
||||
*
|
||||
* @param numBytes byte数组的大小
|
||||
*/
|
||||
public static byte[] generateSalt(int numBytes) {
|
||||
Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes);
|
||||
|
||||
byte[] bytes = new byte[numBytes];
|
||||
random.nextBytes(bytes);
|
||||
return bytes;
|
||||
}
|
||||
|
||||
/**
|
||||
* 对文件进行md5散列.
|
||||
*/
|
||||
public static byte[] md5(InputStream input) throws IOException {
|
||||
return digest(input, MD5);
|
||||
}
|
||||
|
||||
/**
|
||||
* 对文件进行sha1散列.
|
||||
*/
|
||||
public static byte[] sha1(InputStream input) throws IOException {
|
||||
return digest(input, SHA1);
|
||||
}
|
||||
|
||||
private static byte[] digest(InputStream input, String algorithm) throws IOException {
|
||||
try {
|
||||
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
|
||||
int bufferLength = 8 * 1024;
|
||||
byte[] buffer = new byte[bufferLength];
|
||||
int read = input.read(buffer, 0, bufferLength);
|
||||
|
||||
while (read > -1) {
|
||||
messageDigest.update(buffer, 0, read);
|
||||
read = input.read(buffer, 0, bufferLength);
|
||||
}
|
||||
|
||||
return messageDigest.digest();
|
||||
} catch (GeneralSecurityException e) {
|
||||
throw Exceptions.unchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
151
src/main/java/com/nis/util/Encodes.java
Normal file
151
src/main/java/com/nis/util/Encodes.java
Normal file
@@ -0,0 +1,151 @@
|
||||
/**
|
||||
* Copyright (c) 2005-2012 springside.org.cn
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.net.URLDecoder;
|
||||
import java.net.URLEncoder;
|
||||
|
||||
import org.apache.commons.codec.DecoderException;
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.apache.commons.codec.binary.Hex;
|
||||
import org.apache.commons.lang3.StringEscapeUtils;
|
||||
|
||||
/**
|
||||
* 封装各种格式的编码解码工具类.
|
||||
* 1.Commons-Codec的 hex/base64 编码
|
||||
* 2.自制的base62 编码
|
||||
* 3.Commons-Lang的xml/html escape
|
||||
* 4.JDK提供的URLEncoder
|
||||
* @author calvin
|
||||
* @version 2013-01-15
|
||||
*/
|
||||
public class Encodes {
|
||||
|
||||
private static final String DEFAULT_URL_ENCODING = "UTF-8";
|
||||
private static final char[] BASE62 = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz".toCharArray();
|
||||
|
||||
/**
|
||||
* Hex编码.
|
||||
*/
|
||||
public static String encodeHex(byte[] input) {
|
||||
return new String(Hex.encodeHex(input));
|
||||
}
|
||||
|
||||
/**
|
||||
* Hex解码.
|
||||
*/
|
||||
public static byte[] decodeHex(String input) {
|
||||
try {
|
||||
return Hex.decodeHex(input.toCharArray());
|
||||
} catch (DecoderException e) {
|
||||
throw Exceptions.unchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Base64编码.
|
||||
*/
|
||||
public static String encodeBase64(byte[] input) {
|
||||
return new String(Base64.encodeBase64(input));
|
||||
}
|
||||
|
||||
/**
|
||||
* Base64编码.
|
||||
*/
|
||||
public static String encodeBase64(String input) {
|
||||
try {
|
||||
return new String(Base64.encodeBase64(input.getBytes(DEFAULT_URL_ENCODING)));
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
// /**
|
||||
// * Base64编码, URL安全(将Base64中的URL非法字符'+'和'/'转为'-'和'_', 见RFC3548).
|
||||
// */
|
||||
// public static String encodeUrlSafeBase64(byte[] input) {
|
||||
// return Base64.encodeBase64URLSafe(input);
|
||||
// }
|
||||
|
||||
/**
|
||||
* Base64解码.
|
||||
*/
|
||||
public static byte[] decodeBase64(String input) {
|
||||
return Base64.decodeBase64(input.getBytes());
|
||||
}
|
||||
|
||||
/**
|
||||
* Base64解码.
|
||||
*/
|
||||
public static String decodeBase64String(String input) {
|
||||
try {
|
||||
return new String(Base64.decodeBase64(input.getBytes()), DEFAULT_URL_ENCODING);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Base62编码。
|
||||
*/
|
||||
public static String encodeBase62(byte[] input) {
|
||||
char[] chars = new char[input.length];
|
||||
for (int i = 0; i < input.length; i++) {
|
||||
chars[i] = BASE62[((input[i] & 0xFF) % BASE62.length)];
|
||||
}
|
||||
return new String(chars);
|
||||
}
|
||||
|
||||
/**
|
||||
* Html 转码.
|
||||
*/
|
||||
public static String escapeHtml(String html) {
|
||||
return StringEscapeUtils.escapeHtml4(html);
|
||||
}
|
||||
|
||||
/**
|
||||
* Html 解码.
|
||||
*/
|
||||
public static String unescapeHtml(String htmlEscaped) {
|
||||
return StringEscapeUtils.unescapeHtml4(htmlEscaped);
|
||||
}
|
||||
|
||||
/**
|
||||
* Xml 转码.
|
||||
*/
|
||||
public static String escapeXml(String xml) {
|
||||
return StringEscapeUtils.escapeXml10(xml);
|
||||
}
|
||||
|
||||
/**
|
||||
* Xml 解码.
|
||||
*/
|
||||
public static String unescapeXml(String xmlEscaped) {
|
||||
return StringEscapeUtils.unescapeXml(xmlEscaped);
|
||||
}
|
||||
|
||||
/**
|
||||
* URL 编码, Encode默认为UTF-8.
|
||||
*/
|
||||
public static String urlEncode(String part) {
|
||||
try {
|
||||
return URLEncoder.encode(part, DEFAULT_URL_ENCODING);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw Exceptions.unchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* URL 解码, Encode默认为UTF-8.
|
||||
*/
|
||||
public static String urlDecode(String part) {
|
||||
|
||||
try {
|
||||
return URLDecoder.decode(part, DEFAULT_URL_ENCODING);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
throw Exceptions.unchecked(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
72
src/main/java/com/nis/util/Exceptions.java
Normal file
72
src/main/java/com/nis/util/Exceptions.java
Normal file
@@ -0,0 +1,72 @@
|
||||
/**
|
||||
* Copyright (c) 2005-2012 springside.org.cn
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.io.PrintWriter;
|
||||
import java.io.StringWriter;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
/**
|
||||
* 关于异常的工具类.
|
||||
* @author calvin
|
||||
* @version 2013-01-15
|
||||
*/
|
||||
public class Exceptions {
|
||||
|
||||
/**
|
||||
* 将CheckedException转换为UncheckedException.
|
||||
*/
|
||||
public static RuntimeException unchecked(Exception e) {
|
||||
if (e instanceof RuntimeException) {
|
||||
return (RuntimeException) e;
|
||||
} else {
|
||||
return new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将ErrorStack转化为String.
|
||||
*/
|
||||
public static String getStackTraceAsString(Throwable e) {
|
||||
if (e == null){
|
||||
return "";
|
||||
}
|
||||
StringWriter stringWriter = new StringWriter();
|
||||
e.printStackTrace(new PrintWriter(stringWriter));
|
||||
return stringWriter.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 判断异常是否由某些底层的异常引起.
|
||||
*/
|
||||
public static boolean isCausedBy(Exception ex, Class<? extends Exception>... causeExceptionClasses) {
|
||||
Throwable cause = ex.getCause();
|
||||
while (cause != null) {
|
||||
for (Class<? extends Exception> causeClass : causeExceptionClasses) {
|
||||
if (causeClass.isInstance(cause)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
cause = cause.getCause();
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 在request中获取异常类
|
||||
* @param request
|
||||
* @return
|
||||
*/
|
||||
public static Throwable getThrowable(HttpServletRequest request){
|
||||
Throwable ex = null;
|
||||
if (request.getAttribute("exception") != null) {
|
||||
ex = (Throwable) request.getAttribute("exception");
|
||||
} else if (request.getAttribute("javax.servlet.error.exception") != null) {
|
||||
ex = (Throwable) request.getAttribute("javax.servlet.error.exception");
|
||||
}
|
||||
return ex;
|
||||
}
|
||||
|
||||
}
|
||||
731
src/main/java/com/nis/util/FileUtils.java
Normal file
731
src/main/java/com/nis/util/FileUtils.java
Normal file
@@ -0,0 +1,731 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.OutputStream;
|
||||
import java.net.URLEncoder;
|
||||
import java.util.Enumeration;
|
||||
|
||||
import javax.servlet.ServletOutputStream;
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.tools.zip.ZipEntry;
|
||||
import org.apache.tools.zip.ZipFile;
|
||||
import org.apache.tools.zip.ZipOutputStream;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.nis.web.security.Servlets;
|
||||
|
||||
/**
|
||||
* 文件操作工具类 实现文件的创建、删除、复制、压缩、解压以及目录的创建、删除、复制、压缩解压等功能
|
||||
*
|
||||
* @author ThinkGem
|
||||
* @version 2013-06-21
|
||||
*/
|
||||
public class FileUtils extends org.apache.commons.io.FileUtils {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(FileUtils.class);
|
||||
|
||||
/**
|
||||
* 复制单个文件,如果目标文件存在,则不覆盖
|
||||
*
|
||||
* @param srcFileName
|
||||
* 待复制的文件名
|
||||
* @param descFileName
|
||||
* 目标文件名
|
||||
* @return 如果复制成功,则返回true,否则返回false
|
||||
*/
|
||||
public static boolean copyFile(String srcFileName, String descFileName) {
|
||||
return FileUtils.copyFileCover(srcFileName, descFileName, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 复制单个文件
|
||||
*
|
||||
* @param srcFileName
|
||||
* 待复制的文件名
|
||||
* @param descFileName
|
||||
* 目标文件名
|
||||
* @param coverlay
|
||||
* 如果目标文件已存在,是否覆盖
|
||||
* @return 如果复制成功,则返回true,否则返回false
|
||||
*/
|
||||
public static boolean copyFileCover(String srcFileName, String descFileName, boolean coverlay) {
|
||||
File srcFile = new File(srcFileName);
|
||||
// 判断源文件是否存在
|
||||
if (!srcFile.exists()) {
|
||||
log.debug("复制文件失败,源文件 " + srcFileName + " 不存在!");
|
||||
return false;
|
||||
}
|
||||
// 判断源文件是否是合法的文件
|
||||
else if (!srcFile.isFile()) {
|
||||
log.debug("复制文件失败," + srcFileName + " 不是一个文件!");
|
||||
return false;
|
||||
}
|
||||
File descFile = new File(descFileName);
|
||||
// 判断目标文件是否存在
|
||||
if (descFile.exists()) {
|
||||
// 如果目标文件存在,并且允许覆盖
|
||||
if (coverlay) {
|
||||
log.debug("目标文件已存在,准备删除!");
|
||||
if (!FileUtils.delFile(descFileName)) {
|
||||
log.debug("删除目标文件 " + descFileName + " 失败!");
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
log.debug("复制文件失败,目标文件 " + descFileName + " 已存在!");
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
if (!descFile.getParentFile().exists()) {
|
||||
// 如果目标文件所在的目录不存在,则创建目录
|
||||
log.debug("目标文件所在的目录不存在,创建目录!");
|
||||
// 创建目标文件所在的目录
|
||||
if (!descFile.getParentFile().mkdirs()) {
|
||||
log.debug("创建目标文件所在的目录失败!");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 准备复制文件
|
||||
// 读取的位数
|
||||
int readByte = 0;
|
||||
InputStream ins = null;
|
||||
OutputStream outs = null;
|
||||
try {
|
||||
// 打开源文件
|
||||
ins = new FileInputStream(srcFile);
|
||||
// 打开目标文件的输出流
|
||||
outs = new FileOutputStream(descFile);
|
||||
byte[] buf = new byte[1024];
|
||||
// 一次读取1024个字节,当readByte为-1时表示文件已经读取完毕
|
||||
while ((readByte = ins.read(buf)) != -1) {
|
||||
// 将读取的字节流写入到输出流
|
||||
outs.write(buf, 0, readByte);
|
||||
}
|
||||
log.debug("复制单个文件 " + srcFileName + " 到" + descFileName + "成功!");
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.debug("复制文件失败:" + e.getMessage());
|
||||
return false;
|
||||
} finally {
|
||||
// 关闭输入输出流,首先关闭输出流,然后再关闭输入流
|
||||
if (outs != null) {
|
||||
try {
|
||||
outs.close();
|
||||
} catch (IOException oute) {
|
||||
oute.printStackTrace();
|
||||
}
|
||||
}
|
||||
if (ins != null) {
|
||||
try {
|
||||
ins.close();
|
||||
} catch (IOException ine) {
|
||||
ine.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 复制整个目录的内容,如果目标目录存在,则不覆盖
|
||||
*
|
||||
* @param srcDirName
|
||||
* 源目录名
|
||||
* @param descDirName
|
||||
* 目标目录名
|
||||
* @return 如果复制成功返回true,否则返回false
|
||||
*/
|
||||
public static boolean copyDirectory(String srcDirName, String descDirName) {
|
||||
return FileUtils.copyDirectoryCover(srcDirName, descDirName, false);
|
||||
}
|
||||
|
||||
/**
|
||||
* 复制整个目录的内容
|
||||
*
|
||||
* @param srcDirName
|
||||
* 源目录名
|
||||
* @param descDirName
|
||||
* 目标目录名
|
||||
* @param coverlay
|
||||
* 如果目标目录存在,是否覆盖
|
||||
* @return 如果复制成功返回true,否则返回false
|
||||
*/
|
||||
public static boolean copyDirectoryCover(String srcDirName, String descDirName, boolean coverlay) {
|
||||
File srcDir = new File(srcDirName);
|
||||
// 判断源目录是否存在
|
||||
if (!srcDir.exists()) {
|
||||
log.debug("复制目录失败,源目录 " + srcDirName + " 不存在!");
|
||||
return false;
|
||||
}
|
||||
// 判断源目录是否是目录
|
||||
else if (!srcDir.isDirectory()) {
|
||||
log.debug("复制目录失败," + srcDirName + " 不是一个目录!");
|
||||
return false;
|
||||
}
|
||||
// 如果目标文件夹名不以文件分隔符结尾,自动添加文件分隔符
|
||||
String descDirNames = descDirName;
|
||||
if (!descDirNames.endsWith(File.separator)) {
|
||||
descDirNames = descDirNames + File.separator;
|
||||
}
|
||||
File descDir = new File(descDirNames);
|
||||
// 如果目标文件夹存在
|
||||
if (descDir.exists()) {
|
||||
if (coverlay) {
|
||||
// 允许覆盖目标目录
|
||||
log.debug("目标目录已存在,准备删除!");
|
||||
if (!FileUtils.delFile(descDirNames)) {
|
||||
log.debug("删除目录 " + descDirNames + " 失败!");
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
log.debug("目标目录复制失败,目标目录 " + descDirNames + " 已存在!");
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
// 创建目标目录
|
||||
log.debug("目标目录不存在,准备创建!");
|
||||
if (!descDir.mkdirs()) {
|
||||
log.debug("创建目标目录失败!");
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
boolean flag = true;
|
||||
// 列出源目录下的所有文件名和子目录名
|
||||
File[] files = srcDir.listFiles();
|
||||
for (int i = 0; i < files.length; i++) {
|
||||
// 如果是一个单个文件,则直接复制
|
||||
if (files[i].isFile()) {
|
||||
flag = FileUtils.copyFile(files[i].getAbsolutePath(), descDirName + files[i].getName());
|
||||
// 如果拷贝文件失败,则退出循环
|
||||
if (!flag) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// 如果是子目录,则继续复制目录
|
||||
if (files[i].isDirectory()) {
|
||||
flag = FileUtils.copyDirectory(files[i].getAbsolutePath(), descDirName + files[i].getName());
|
||||
// 如果拷贝目录失败,则退出循环
|
||||
if (!flag) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!flag) {
|
||||
log.debug("复制目录 " + srcDirName + " 到 " + descDirName + " 失败!");
|
||||
return false;
|
||||
}
|
||||
log.debug("复制目录 " + srcDirName + " 到 " + descDirName + " 成功!");
|
||||
return true;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* 删除文件,可以删除单个文件或文件夹
|
||||
*
|
||||
* @param fileName
|
||||
* 被删除的文件名
|
||||
* @return 如果删除成功,则返回true,否是返回false
|
||||
*/
|
||||
public static boolean delFile(String fileName) {
|
||||
File file = new File(fileName);
|
||||
if (!file.exists()) {
|
||||
log.debug(fileName + " 文件不存在!");
|
||||
return true;
|
||||
} else {
|
||||
if (file.isFile()) {
|
||||
return FileUtils.deleteFile(fileName);
|
||||
} else {
|
||||
return FileUtils.deleteDirectory(fileName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* 删除单个文件
|
||||
*
|
||||
* @param fileName
|
||||
* 被删除的文件名
|
||||
* @return 如果删除成功,则返回true,否则返回false
|
||||
*/
|
||||
public static boolean deleteFile(String fileName) {
|
||||
File file = new File(fileName);
|
||||
if (file.exists() && file.isFile()) {
|
||||
if (file.delete()) {
|
||||
log.debug("删除文件 " + fileName + " 成功!");
|
||||
return true;
|
||||
} else {
|
||||
log.debug("删除文件 " + fileName + " 失败!");
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
log.debug(fileName + " 文件不存在!");
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* 删除目录及目录下的文件
|
||||
*
|
||||
* @param dirName
|
||||
* 被删除的目录所在的文件路径
|
||||
* @return 如果目录删除成功,则返回true,否则返回false
|
||||
*/
|
||||
public static boolean deleteDirectory(String dirName) {
|
||||
String dirNames = dirName;
|
||||
if (!dirNames.endsWith(File.separator)) {
|
||||
dirNames = dirNames + File.separator;
|
||||
}
|
||||
File dirFile = new File(dirNames);
|
||||
if (!dirFile.exists() || !dirFile.isDirectory()) {
|
||||
log.debug(dirNames + " 目录不存在!");
|
||||
return true;
|
||||
}
|
||||
boolean flag = true;
|
||||
// 列出全部文件及子目录
|
||||
File[] files = dirFile.listFiles();
|
||||
for (int i = 0; i < files.length; i++) {
|
||||
// 删除子文件
|
||||
if (files[i].isFile()) {
|
||||
flag = FileUtils.deleteFile(files[i].getAbsolutePath());
|
||||
// 如果删除文件失败,则退出循环
|
||||
if (!flag) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
// 删除子目录
|
||||
else if (files[i].isDirectory()) {
|
||||
flag = FileUtils.deleteDirectory(files[i].getAbsolutePath());
|
||||
// 如果删除子目录失败,则退出循环
|
||||
if (!flag) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!flag) {
|
||||
log.debug("删除目录失败!");
|
||||
return false;
|
||||
}
|
||||
// 删除当前目录
|
||||
if (dirFile.delete()) {
|
||||
log.debug("删除目录 " + dirName + " 成功!");
|
||||
return true;
|
||||
} else {
|
||||
log.debug("删除目录 " + dirName + " 失败!");
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建单个文件
|
||||
*
|
||||
* @param descFileName
|
||||
* 文件名,包含路径
|
||||
* @return 如果创建成功,则返回true,否则返回false
|
||||
*/
|
||||
public static boolean createFile(String descFileName) {
|
||||
File file = new File(descFileName);
|
||||
if (file.exists()) {
|
||||
log.debug("文件 " + descFileName + " 已存在!");
|
||||
return false;
|
||||
}
|
||||
if (descFileName.endsWith(File.separator)) {
|
||||
log.debug(descFileName + " 为目录,不能创建目录!");
|
||||
return false;
|
||||
}
|
||||
if (!file.getParentFile().exists()) {
|
||||
// 如果文件所在的目录不存在,则创建目录
|
||||
if (!file.getParentFile().mkdirs()) {
|
||||
log.debug("创建文件所在的目录失败!");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 创建文件
|
||||
try {
|
||||
if (file.createNewFile()) {
|
||||
log.debug(descFileName + " 文件创建成功!");
|
||||
return true;
|
||||
} else {
|
||||
log.debug(descFileName + " 文件创建失败!");
|
||||
return false;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
log.debug(descFileName + " 文件创建失败!");
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建目录
|
||||
*
|
||||
* @param descDirName
|
||||
* 目录名,包含路径
|
||||
* @return 如果创建成功,则返回true,否则返回false
|
||||
*/
|
||||
public static boolean createDirectory(String descDirName) {
|
||||
String descDirNames = descDirName;
|
||||
if (!descDirNames.endsWith(File.separator)) {
|
||||
descDirNames = descDirNames + File.separator;
|
||||
}
|
||||
File descDir = new File(descDirNames);
|
||||
if (descDir.exists()) {
|
||||
log.debug("目录 " + descDirNames + " 已存在!");
|
||||
return false;
|
||||
}
|
||||
// 创建目录
|
||||
if (descDir.mkdirs()) {
|
||||
log.debug("目录 " + descDirNames + " 创建成功!");
|
||||
return true;
|
||||
} else {
|
||||
log.debug("目录 " + descDirNames + " 创建失败!");
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入文件
|
||||
*
|
||||
* @param file
|
||||
* 要写入的文件
|
||||
*/
|
||||
public static void writeToFile(String fileName, String content, boolean append) {
|
||||
try {
|
||||
FileUtils.write(new File(fileName), content, "utf-8", append);
|
||||
log.debug("文件 " + fileName + " 写入成功!");
|
||||
} catch (IOException e) {
|
||||
log.debug("文件 " + fileName + " 写入失败! " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 写入文件
|
||||
*
|
||||
* @param file
|
||||
* 要写入的文件
|
||||
*/
|
||||
public static void writeToFile(String fileName, String content, String encoding, boolean append) {
|
||||
try {
|
||||
FileUtils.write(new File(fileName), content, encoding, append);
|
||||
log.debug("文件 " + fileName + " 写入成功!");
|
||||
} catch (IOException e) {
|
||||
log.debug("文件 " + fileName + " 写入失败! " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 压缩文件或目录
|
||||
*
|
||||
* @param srcDirName
|
||||
* 压缩的根目录
|
||||
* @param fileName
|
||||
* 根目录下的待压缩的文件名或文件夹名,其中*或""表示跟目录下的全部文件
|
||||
* @param descFileName
|
||||
* 目标zip文件
|
||||
*/
|
||||
public static void zipFiles(String srcDirName, String fileName, String descFileName) {
|
||||
// 判断目录是否存在
|
||||
if (srcDirName == null) {
|
||||
log.debug("文件压缩失败,目录 " + srcDirName + " 不存在!");
|
||||
return;
|
||||
}
|
||||
File fileDir = new File(srcDirName);
|
||||
if (!fileDir.exists() || !fileDir.isDirectory()) {
|
||||
log.debug("文件压缩失败,目录 " + srcDirName + " 不存在!");
|
||||
return;
|
||||
}
|
||||
String dirPath = fileDir.getAbsolutePath();
|
||||
File descFile = new File(descFileName);
|
||||
try {
|
||||
ZipOutputStream zouts = new ZipOutputStream(new FileOutputStream(descFile));
|
||||
if ("*".equals(fileName) || "".equals(fileName)) {
|
||||
FileUtils.zipDirectoryToZipFile(dirPath, fileDir, zouts);
|
||||
} else {
|
||||
File file = new File(fileDir, fileName);
|
||||
if (file.isFile()) {
|
||||
FileUtils.zipFilesToZipFile(dirPath, file, zouts);
|
||||
} else {
|
||||
FileUtils.zipDirectoryToZipFile(dirPath, file, zouts);
|
||||
}
|
||||
}
|
||||
zouts.close();
|
||||
log.debug(descFileName + " 文件压缩成功!");
|
||||
} catch (Exception e) {
|
||||
log.debug("文件压缩失败:" + e.getMessage());
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 解压缩ZIP文件,将ZIP文件里的内容解压到descFileName目录下
|
||||
*
|
||||
* @param zipFileName
|
||||
* 需要解压的ZIP文件
|
||||
* @param descFileName
|
||||
* 目标文件
|
||||
*/
|
||||
public static boolean unZipFiles(String zipFileName, String descFileName) {
|
||||
String descFileNames = descFileName;
|
||||
if (!descFileNames.endsWith(File.separator)) {
|
||||
descFileNames = descFileNames + File.separator;
|
||||
}
|
||||
try {
|
||||
// 根据ZIP文件创建ZipFile对象
|
||||
ZipFile zipFile = new ZipFile(zipFileName);
|
||||
ZipEntry entry = null;
|
||||
String entryName = null;
|
||||
String descFileDir = null;
|
||||
byte[] buf = new byte[4096];
|
||||
int readByte = 0;
|
||||
// 获取ZIP文件里所有的entry
|
||||
@SuppressWarnings("rawtypes")
|
||||
Enumeration enums = zipFile.getEntries();
|
||||
// 遍历所有entry
|
||||
while (enums.hasMoreElements()) {
|
||||
entry = (ZipEntry) enums.nextElement();
|
||||
// 获得entry的名字
|
||||
entryName = entry.getName();
|
||||
descFileDir = descFileNames + entryName;
|
||||
if (entry.isDirectory()) {
|
||||
// 如果entry是一个目录,则创建目录
|
||||
new File(descFileDir).mkdirs();
|
||||
continue;
|
||||
} else {
|
||||
// 如果entry是一个文件,则创建父目录
|
||||
new File(descFileDir).getParentFile().mkdirs();
|
||||
}
|
||||
File file = new File(descFileDir);
|
||||
// 打开文件输出流
|
||||
OutputStream os = new FileOutputStream(file);
|
||||
// 从ZipFile对象中打开entry的输入流
|
||||
InputStream is = zipFile.getInputStream(entry);
|
||||
while ((readByte = is.read(buf)) != -1) {
|
||||
os.write(buf, 0, readByte);
|
||||
}
|
||||
os.close();
|
||||
is.close();
|
||||
}
|
||||
zipFile.close();
|
||||
log.debug("文件解压成功!");
|
||||
return true;
|
||||
} catch (Exception e) {
|
||||
log.debug("文件解压失败:" + e.getMessage());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将目录压缩到ZIP输出流
|
||||
*
|
||||
* @param dirPath
|
||||
* 目录路径
|
||||
* @param fileDir
|
||||
* 文件信息
|
||||
* @param zouts
|
||||
* 输出流
|
||||
*/
|
||||
public static void zipDirectoryToZipFile(String dirPath, File fileDir, ZipOutputStream zouts) {
|
||||
if (fileDir.isDirectory()) {
|
||||
File[] files = fileDir.listFiles();
|
||||
// 空的文件夹
|
||||
if (files.length == 0) {
|
||||
// 目录信息
|
||||
ZipEntry entry = new ZipEntry(getEntryName(dirPath, fileDir));
|
||||
try {
|
||||
zouts.putNextEntry(entry);
|
||||
zouts.closeEntry();
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
for (int i = 0; i < files.length; i++) {
|
||||
if (files[i].isFile()) {
|
||||
// 如果是文件,则调用文件压缩方法
|
||||
FileUtils.zipFilesToZipFile(dirPath, files[i], zouts);
|
||||
} else {
|
||||
// 如果是目录,则递归调用
|
||||
FileUtils.zipDirectoryToZipFile(dirPath, files[i], zouts);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 将文件压缩到ZIP输出流
|
||||
*
|
||||
* @param dirPath
|
||||
* 目录路径
|
||||
* @param file
|
||||
* 文件
|
||||
* @param zouts
|
||||
* 输出流
|
||||
*/
|
||||
public static void zipFilesToZipFile(String dirPath, File file, ZipOutputStream zouts) {
|
||||
FileInputStream fin = null;
|
||||
ZipEntry entry = null;
|
||||
// 创建复制缓冲区
|
||||
byte[] buf = new byte[4096];
|
||||
int readByte = 0;
|
||||
if (file.isFile()) {
|
||||
try {
|
||||
// 创建一个文件输入流
|
||||
fin = new FileInputStream(file);
|
||||
// 创建一个ZipEntry
|
||||
entry = new ZipEntry(getEntryName(dirPath, file));
|
||||
// 存储信息到压缩文件
|
||||
zouts.putNextEntry(entry);
|
||||
// 复制字节到压缩文件
|
||||
while ((readByte = fin.read(buf)) != -1) {
|
||||
zouts.write(buf, 0, readByte);
|
||||
}
|
||||
zouts.closeEntry();
|
||||
fin.close();
|
||||
System.out.println("添加文件 " + file.getAbsolutePath() + " 到zip文件中!");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取待压缩文件在ZIP文件中entry的名字,即相对于跟目录的相对路径名
|
||||
*
|
||||
* @param dirPat
|
||||
* 目录名
|
||||
* @param file
|
||||
* entry文件名
|
||||
* @return
|
||||
*/
|
||||
private static String getEntryName(String dirPath, File file) {
|
||||
String dirPaths = dirPath;
|
||||
if (!dirPaths.endsWith(File.separator)) {
|
||||
dirPaths = dirPaths + File.separator;
|
||||
}
|
||||
String filePath = file.getAbsolutePath();
|
||||
// 对于目录,必须在entry名字后面加上"/",表示它将以目录项存储
|
||||
if (file.isDirectory()) {
|
||||
filePath += "/";
|
||||
}
|
||||
int index = filePath.indexOf(dirPaths);
|
||||
|
||||
return filePath.substring(index + dirPaths.length());
|
||||
}
|
||||
|
||||
/**
|
||||
* 修复路径,将 \\ 或 / 等替换为 File.separator
|
||||
*
|
||||
* @param path
|
||||
* @return
|
||||
*/
|
||||
public static String path(String path) {
|
||||
String p = StringUtils.replace(path, "\\", "/");
|
||||
// p = StringUtils.join(StringUtils.split(p, "/"), "/");
|
||||
if (!StringUtils.startsWithAny(p, "/") && StringUtils.startsWithAny(path, "\\", "/")) {
|
||||
p += "/";
|
||||
}
|
||||
if (!StringUtils.endsWithAny(p, "/") && StringUtils.endsWithAny(path, "\\", "/")) {
|
||||
p = p + "/";
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取文件唯一名称
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static String getFileKey() {
|
||||
String suffixName = DateUtils.getDate("hhmmss");
|
||||
return StringUtil.createUUID() + suffixName;
|
||||
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 获取文件后缀
|
||||
*
|
||||
* @param filename
|
||||
* @param isDot
|
||||
* true:加“.”
|
||||
* @return
|
||||
*/
|
||||
public static String getSuffix(String filename, Boolean isDot) {
|
||||
String suffix = "";
|
||||
int pos = filename.lastIndexOf('.');
|
||||
if (pos > 0 && pos < filename.length() - 1) {
|
||||
if (!isDot) {
|
||||
pos = pos + 1;
|
||||
}
|
||||
suffix = filename.substring(pos);
|
||||
}
|
||||
return suffix;
|
||||
}
|
||||
|
||||
// 文件下载
|
||||
public static void fileDownload(HttpServletRequest request,
|
||||
HttpServletResponse response,
|
||||
String filename,
|
||||
String filepath) throws IOException{
|
||||
FileInputStream in = null;
|
||||
ServletOutputStream out = null;
|
||||
try {
|
||||
String path = FileUtils.path(Servlets.getRequest().getServletContext().getRealPath(filepath));
|
||||
File src = new File(path);
|
||||
in = new FileInputStream(src);
|
||||
response.reset();
|
||||
response.setCharacterEncoding("UTF-8");
|
||||
if (request.getHeader("User-Agent").toLowerCase().indexOf("firefox") > 0) {
|
||||
filename = new String(filename.getBytes("UTF-8"), "ISO8859-1");
|
||||
response.setHeader("Content-Disposition", "attachment;filename=\"" + filename + "\"");
|
||||
}
|
||||
// IE
|
||||
else if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0
|
||||
|| request.getHeader("User-Agent").toUpperCase().indexOf("LIKE GECKO") > 0) {
|
||||
filename = URLEncoder.encode(filename, "UTF-8");
|
||||
response.setHeader("Content-Disposition", "attachment; filename=" + filename);
|
||||
}
|
||||
out = response.getOutputStream();
|
||||
byte[] buffer = new byte[1024];
|
||||
int len = 0;
|
||||
while ((len = in.read(buffer, 0, 1024)) != -1) {
|
||||
out.write(buffer, 0, len);
|
||||
}
|
||||
out.flush();
|
||||
} finally {
|
||||
if (in != null) {
|
||||
in.close();
|
||||
in=null;
|
||||
}
|
||||
if (out != null) {
|
||||
out.close();
|
||||
out=null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
79
src/main/java/com/nis/util/FormatUtils.java
Normal file
79
src/main/java/com/nis/util/FormatUtils.java
Normal file
@@ -0,0 +1,79 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
|
||||
public class FormatUtils {
|
||||
|
||||
/**
|
||||
* 将List<HashMap<String,Object>>中HashMap的key全部转化为变量形式,<br>
|
||||
* 如{"BRH_ID":"1234","BRH_NAME":"机构"}改为{"brhId":"1234","brhName":"机构"}
|
||||
*
|
||||
* @param list
|
||||
* @return
|
||||
*/
|
||||
public static List<HashMap<String, Object>> formatHashMapKeyInList(
|
||||
List<HashMap<String, Object>> list) {
|
||||
List result = new ArrayList();
|
||||
// 遍历list后进行格式化列表元素
|
||||
if (list!=null){
|
||||
for (HashMap<String, Object> h : list) {
|
||||
// 将hashMap的key转化为驼峰格式,如{"BRH_ID":"1234"}改为{"brhId":"1234"}
|
||||
result.add(formatHashMapKey(h));
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将hashMap的key转化为驼峰格式,如{"BRH_ID":"1234","BRH_NAME":"机构"}改为{"brhId":"1234",
|
||||
* "brhName":"机构"}
|
||||
*
|
||||
* @param hashMap
|
||||
* @return
|
||||
*/
|
||||
public static HashMap<String, Object> formatHashMapKey(
|
||||
HashMap<String, Object> hashMap) {
|
||||
HashMap result = new HashMap();
|
||||
String key = null;
|
||||
// 遍历map
|
||||
for (Entry<String, Object> e : (Set<Entry<String, Object>>) hashMap.entrySet()) {
|
||||
key = (String) e.getKey();
|
||||
// 将hashMap的key转化为驼峰格式
|
||||
key = formatDBNameToVarName(key);
|
||||
// 封装为新的map
|
||||
result.put(key, e.getValue());
|
||||
}
|
||||
// 返回格式化后的map
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 数据库列名转化为属性名,如DEAL_ID=dealId; <br>
|
||||
* 不能保证完全正确,如DBUTIL不会智能的转化为DBUtil,而会转化为dbutil, <br>
|
||||
* 规则为全部转化为单词,然后首字母小写
|
||||
*
|
||||
* @param DBName
|
||||
* @return
|
||||
*/
|
||||
public static String formatDBNameToVarName(String DBName) {
|
||||
StringBuilder result = new StringBuilder("");
|
||||
// 以"_"分割
|
||||
String[] DBNameArr = DBName.split("_");
|
||||
for (int i = 0, j = DBNameArr.length; i < j; i++) {
|
||||
// 获取以"_"分割后的字符数组的每个元素的第一个字母,
|
||||
result.append(DBNameArr[i].charAt(0));
|
||||
// 将其他字符转换成小写
|
||||
result.append(DBNameArr[i].substring(1).toLowerCase());
|
||||
}
|
||||
char c0 = result.charAt(0);
|
||||
if (c0 >= 'A' && c0 <= 'Z')
|
||||
c0 = (char) (c0 + 'a' - 'A');
|
||||
result.setCharAt(0, c0);
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
}
|
||||
57
src/main/java/com/nis/util/HiveDataSource.java
Normal file
57
src/main/java/com/nis/util/HiveDataSource.java
Normal file
@@ -0,0 +1,57 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.sql.Connection;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.Statement;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.springframework.context.ApplicationContext;
|
||||
import org.springframework.context.support.ClassPathXmlApplicationContext;
|
||||
import com.jolbox.bonecp.BoneCPDataSource;
|
||||
|
||||
public class HiveDataSource {
|
||||
private final static Logger logger = Logger.getLogger(HiveDataSource.class);
|
||||
static Connection conn = null;
|
||||
static ResultSet rsA = null;
|
||||
static Statement stA = null;
|
||||
|
||||
static ResultSet rsB = null;
|
||||
static Statement stB = null;
|
||||
|
||||
public static ResultSet query(String sql, String searchActiveSys) throws Exception {
|
||||
if (null != searchActiveSys && searchActiveSys.equals("4")) {// A版数据库
|
||||
logger.info("开始连接数据中心A版日志库--------------------------");
|
||||
if (conn == null || conn.isClosed()) {
|
||||
ApplicationContext ct = new ClassPathXmlApplicationContext("applicationContext-mybatis.xml");
|
||||
BoneCPDataSource datasource = (BoneCPDataSource) ct.getBean("HiveADataSource");
|
||||
conn = datasource.getConnection();
|
||||
}
|
||||
logger.info("连接数据中心A版日志库成功--------------------------");
|
||||
stA = conn.createStatement();
|
||||
String hiveAName = "use " + Constants.HIVEADBNAME;
|
||||
// stA.execute("use xa_dfbhit_p_hive");
|
||||
stA.execute(hiveAName);
|
||||
logger.info("开始执行查询数据中心A版日志库操作--------------------------" + sql);
|
||||
rsA = stA.executeQuery(sql);
|
||||
logger.info("执行查询数据中心A版日志库成功--------------------------");
|
||||
return rsA;
|
||||
} else {// 目前默认B版数据库,后期增加C版数据库
|
||||
logger.info("开始连接数据中心B版日志库--------------------------");
|
||||
if (conn == null || conn.isClosed()) {
|
||||
ApplicationContext ct = new ClassPathXmlApplicationContext("applicationContext-mybatis.xml");
|
||||
BoneCPDataSource datasource = (BoneCPDataSource) ct.getBean("HiveBDataSource");
|
||||
conn = datasource.getConnection();
|
||||
}
|
||||
logger.info("连接数据中心B版日志库成功--------------------------");
|
||||
stB = conn.createStatement();
|
||||
String hiveBName = "use " + Constants.HIVEBDBNAME;
|
||||
// stB.execute("use xa_z2_mesalog_hive");
|
||||
stB.execute(hiveBName);
|
||||
logger.info("开始执行查询数据中心B版日志库操作--------------------------" + sql);
|
||||
rsB = stB.executeQuery(sql);
|
||||
logger.info("执行查询数据中心B版日志库成功--------------------------");
|
||||
return rsB;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
291
src/main/java/com/nis/util/HiveJDBC.java
Normal file
291
src/main/java/com/nis/util/HiveJDBC.java
Normal file
@@ -0,0 +1,291 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.beans.BeanInfo;
|
||||
import java.beans.Introspector;
|
||||
import java.beans.PropertyDescriptor;
|
||||
import java.io.IOException;
|
||||
import java.math.BigDecimal;
|
||||
import java.sql.Connection;
|
||||
import java.sql.DriverManager;
|
||||
import java.sql.ResultSet;
|
||||
import java.sql.ResultSetMetaData;
|
||||
import java.sql.SQLException;
|
||||
import java.sql.Statement;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.ibatis.mapping.ResultMap;
|
||||
import org.apache.ibatis.mapping.ResultMapping;
|
||||
import org.apache.ibatis.session.SqlSessionFactory;
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.nis.domain.Page;
|
||||
import com.nis.util.redis.SaveRedisListThread;
|
||||
import com.nis.web.service.SpringContextHolder;
|
||||
|
||||
public class HiveJDBC {
|
||||
private final static Logger logger = Logger.getLogger(HiveJDBC.class);
|
||||
static Connection conn = null;
|
||||
static ResultSet rs = null;
|
||||
static Statement st = null;
|
||||
static Properties prop = new Properties();
|
||||
static String driverName = "";
|
||||
static String url = "";
|
||||
static String username = "";
|
||||
static String password = "";
|
||||
static {
|
||||
try {
|
||||
prop.load(Configurations.class.getResourceAsStream("/jdbc.properties"));
|
||||
} catch (IOException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
public static void getConn(String searchActiveSys) throws Exception {
|
||||
|
||||
if (null != searchActiveSys && searchActiveSys.equals("4")) {
|
||||
driverName = prop.getProperty("jdbc.hiveA.driver").trim();
|
||||
url = prop.getProperty("jdbc.hiveA.url").trim();
|
||||
username = prop.getProperty("jdbc.hiveA.username").trim();
|
||||
password = prop.getProperty("jdbc.hiveA.password").trim();
|
||||
} else {
|
||||
driverName = prop.getProperty("jdbc.hiveB.driver").trim();
|
||||
url = prop.getProperty("jdbc.hiveB.url").trim();
|
||||
username = prop.getProperty("jdbc.hiveB.username").trim();
|
||||
password = prop.getProperty("jdbc.hiveB.password").trim();
|
||||
}
|
||||
Class.forName(driverName);
|
||||
conn = DriverManager.getConnection(url, username, password);
|
||||
|
||||
}
|
||||
|
||||
public static ResultSet query(String sql, String searchActiveSys) throws Exception {
|
||||
logger.info("开始连接数据中心日志库--------------------------");
|
||||
getConn(searchActiveSys);
|
||||
logger.info("连接数据中心日志库成功--------------------------");
|
||||
st = conn.createStatement();
|
||||
if (null != searchActiveSys && searchActiveSys.equals("4")) {
|
||||
st.execute("use xa_dfbhit_hive");
|
||||
} else {
|
||||
st.execute("use xa_z2_mesalog_hive");
|
||||
}
|
||||
rs = st.executeQuery(sql);
|
||||
return rs;
|
||||
}
|
||||
|
||||
public static void closeConn() {
|
||||
try {
|
||||
if (rs != null) {
|
||||
rs.close();
|
||||
rs = null;
|
||||
}
|
||||
if (st != null) {
|
||||
st.close();
|
||||
st = null;
|
||||
}
|
||||
if (conn != null) {
|
||||
conn.close();
|
||||
conn = null;
|
||||
}
|
||||
logger.info("关闭数据中心连接成功");
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
logger.error("关闭数据中心连接失败,失败原因" + e);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) throws SQLException {
|
||||
try {
|
||||
// System.out.println(sdf.parse("2016-09-10 10:20:22").getTime());
|
||||
// ResultSet rs = query("");
|
||||
Map map = new HashMap();
|
||||
map.put("time", new Date());
|
||||
map.put("index", 1);
|
||||
for (Object key : map.keySet()) {
|
||||
Object obj = map.get(key);
|
||||
System.out.println(obj);
|
||||
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 将结果利用反射映射成对象集合
|
||||
*
|
||||
* @param rs
|
||||
* resultSet
|
||||
* @param entityClass
|
||||
* 实体类
|
||||
* @param obj
|
||||
* 那些字段需要转换为date类型(由于数据中心表结构中没有date类型数据,其日期用long型表示,界面中需要显示yyyy-MM-dd
|
||||
* hh:mm:ss形式,所以需要将long转换为date)
|
||||
* @return
|
||||
* @throws Exception
|
||||
*/
|
||||
public static Map<String, List> tableMapping(Page page, String redisKey, ResultSet rs, Class entityClass,
|
||||
Object... obj) throws Exception {
|
||||
Map<String, List> mapList = new HashMap<String, List>();
|
||||
Map<String, String> filedAndColumnMap = getColumn2FiledMap(entityClass);
|
||||
List<String> listString = new ArrayList<String>();
|
||||
List listObject = new ArrayList();
|
||||
List<String> columnList = null;
|
||||
if (null != obj && obj.length > 0) {
|
||||
columnList = new ArrayList<String>();
|
||||
for (int i = 0; i < obj.length; i++) {
|
||||
columnList.add(obj[i].toString().toLowerCase());
|
||||
}
|
||||
}
|
||||
// ResultSet rs = HiveJDBC.query(sql.toString());
|
||||
ResultSetMetaData metaData = rs.getMetaData();
|
||||
while (rs.next()) {
|
||||
Map map = new HashMap();
|
||||
for (int i = 1; i <= metaData.getColumnCount(); i++) {
|
||||
Object value = rs.getObject(i);
|
||||
String filedName = filedAndColumnMap.get(metaData.getColumnName(i).toString().toLowerCase());
|
||||
if (null != value) {
|
||||
if (null != columnList && columnList.contains(filedName.toLowerCase())) {
|
||||
long time = 0l;
|
||||
if (null != value && !value.toString().equals("")) {
|
||||
time = Long.parseLong(value.toString());
|
||||
}
|
||||
map.put(filedName, new Date(time * 1000));
|
||||
// map.put(filedName, new
|
||||
// Date(Long.parseLong("1476583810000")));
|
||||
} else {
|
||||
map.put(filedName, value);
|
||||
}
|
||||
} else {
|
||||
map.put(filedName, null);
|
||||
}
|
||||
}
|
||||
listString.add(JsonMapper.toJsonString(map2Obj(map, entityClass)));
|
||||
listObject.add(map2Obj(map, entityClass));
|
||||
}
|
||||
logger.info("开始关闭数据中心连接");
|
||||
HiveJDBC.closeConn();
|
||||
if (null == listString || listString.size() == 0 || null == listObject || listObject.size() == 0) {
|
||||
return null;
|
||||
} else {
|
||||
if (Constants.IS_OPEN_REDIS && Constants.DATACENTER_OPEN_REDIS) {
|
||||
new SaveRedisListThread(redisKey, listString, Constants.HIVE_EXPIRE).start();
|
||||
}
|
||||
}
|
||||
// sublist包前不包后,0-30实际获取的是0-29的数据
|
||||
Integer startNum = (page.getPageNo() - 1) * page.getPageSize();
|
||||
Integer endNum = startNum - 1 + page.getPageSize() + 1;
|
||||
if (listString.size() >= startNum) {
|
||||
if (listString.size() >= endNum) {
|
||||
mapList.put("str", listString.subList(startNum, endNum));
|
||||
} else {
|
||||
mapList.put("str", listString.subList(startNum, listString.size()));
|
||||
}
|
||||
} else {
|
||||
mapList.put("str", new ArrayList());
|
||||
}
|
||||
if (listObject.size() >= startNum) {
|
||||
if (listObject.size() >= endNum) {
|
||||
mapList.put("obj", listObject.subList(startNum, endNum));
|
||||
} else {
|
||||
mapList.put("obj", listObject.subList(startNum, listObject.size()));
|
||||
}
|
||||
|
||||
} else {
|
||||
mapList.put("obj", new ArrayList());
|
||||
}
|
||||
return mapList;
|
||||
}
|
||||
|
||||
public static Object map2Obj(Map map, Class type) throws Exception {
|
||||
BeanInfo beanInfo = Introspector.getBeanInfo(type);
|
||||
Object obj = type.newInstance();
|
||||
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
|
||||
for (int i = 0; i < propertyDescriptors.length; i++) {
|
||||
PropertyDescriptor propertyDescriptor = propertyDescriptors[i];
|
||||
String name = propertyDescriptor.getName();
|
||||
String fieldTypeName = propertyDescriptor.getPropertyType().getName();
|
||||
if (map.containsKey(name)) {
|
||||
Object value = map.get(name);
|
||||
if (null != value && !value.equals("")) {
|
||||
if (fieldTypeName.equals("java.lang.String")) {
|
||||
propertyDescriptor.getWriteMethod().invoke(obj, new String[] { value.toString() });
|
||||
} else if (fieldTypeName.equals("java.lang.Integer")) {
|
||||
propertyDescriptor.getWriteMethod().invoke(obj,
|
||||
new Integer[] { Integer.parseInt(value.toString()) });
|
||||
// propertyDescriptor.getWriteMethod().invoke(obj, new
|
||||
// Integer[] { 0 });
|
||||
} else if (fieldTypeName.equals("java.lang.Long")) {
|
||||
propertyDescriptor.getWriteMethod().invoke(obj,
|
||||
new Long[] { Long.parseLong(value.toString()) });
|
||||
// propertyDescriptor.getWriteMethod().invoke(obj, new
|
||||
// Long[] { 0l });
|
||||
} else if (fieldTypeName.equals("java.lang.Boolean")) {
|
||||
propertyDescriptor.getWriteMethod().invoke(obj,
|
||||
new Boolean[] { Boolean.parseBoolean(value.toString()) });
|
||||
} else if (fieldTypeName.equals("java.lang.Character")) {
|
||||
propertyDescriptor.getWriteMethod().invoke(obj, value.toString().toCharArray());
|
||||
} else if (fieldTypeName.equals("java.lang.Byte")) {
|
||||
propertyDescriptor.getWriteMethod().invoke(obj, value.toString().getBytes());
|
||||
} else if (fieldTypeName.equals("java.lang.Short")) {
|
||||
propertyDescriptor.getWriteMethod().invoke(obj,
|
||||
new Short[] { Short.parseShort(value.toString()) });
|
||||
} else if (fieldTypeName.equals("java.lang.Float")) {
|
||||
propertyDescriptor.getWriteMethod().invoke(obj,
|
||||
new Float[] { Float.parseFloat(value.toString()) });
|
||||
} else if (fieldTypeName.equals("java.lang.Double")) {
|
||||
propertyDescriptor.getWriteMethod().invoke(obj,
|
||||
new Double[] { Double.parseDouble(value.toString()) });
|
||||
} else if (fieldTypeName.equals("java.math.BigDecimal")) {
|
||||
propertyDescriptor.getWriteMethod().invoke(obj,
|
||||
new BigDecimal[] { BigDecimal.valueOf(Long.parseLong(value.toString())) });
|
||||
// propertyDescriptor.getWriteMethod().invoke(obj, new
|
||||
// BigDecimal[] { new BigDecimal(0) });
|
||||
} else if (fieldTypeName.equals("java.util.Date")) {
|
||||
propertyDescriptor.getWriteMethod().invoke(obj, new Date[] { (Date) value });
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return obj;
|
||||
|
||||
}
|
||||
|
||||
public static Map<String, String> getColumn2FiledMap(Class clazz) {
|
||||
Map<String, String> map = new HashMap<String, String>();
|
||||
SqlSessionFactory sqlSessionFactory = SpringContextHolder.getBean(SqlSessionFactory.class);
|
||||
ResultMap resultMap = sqlSessionFactory.getConfiguration().getResultMap(clazz.getSimpleName() + "Map");
|
||||
List<ResultMapping> mapping = resultMap.getResultMappings();
|
||||
for (ResultMapping mapp : mapping) {
|
||||
map.put(mapp.getColumn().toLowerCase(), mapp.getProperty());
|
||||
}
|
||||
return map;
|
||||
|
||||
}
|
||||
|
||||
public static void close() {
|
||||
try {
|
||||
if (rs != null) {
|
||||
rs.close();
|
||||
rs = null;
|
||||
}
|
||||
if (st != null) {
|
||||
st.close();
|
||||
st = null;
|
||||
}
|
||||
if (conn != null) {
|
||||
conn.close();
|
||||
conn = null;
|
||||
}
|
||||
} catch (SQLException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
63
src/main/java/com/nis/util/ImageGeo.java
Normal file
63
src/main/java/com/nis/util/ImageGeo.java
Normal file
@@ -0,0 +1,63 @@
|
||||
package com.nis.util;
|
||||
|
||||
import com.drew.metadata.*;
|
||||
import com.drew.metadata.exif.*;
|
||||
import com.drew.imaging.jpeg.*;
|
||||
import com.drew.lang.*;
|
||||
import java.io.*;
|
||||
|
||||
public class ImageGeo {
|
||||
public double lat = 0.0;
|
||||
public double lon = 0.0;
|
||||
public double alt = 0.0;
|
||||
public boolean error = false;
|
||||
|
||||
public ImageGeo(String filename) {
|
||||
try {
|
||||
error = false;
|
||||
File jpegFile = new File(filename);
|
||||
Metadata metadata = JpegMetadataReader.readMetadata(jpegFile);
|
||||
|
||||
GpsDirectory gpsdir = (GpsDirectory) metadata
|
||||
.getDirectory(GpsDirectory.class);
|
||||
Rational latpart[] = gpsdir
|
||||
.getRationalArray(GpsDirectory.TAG_GPS_LATITUDE);
|
||||
Rational lonpart[] = gpsdir
|
||||
.getRationalArray(GpsDirectory.TAG_GPS_LONGITUDE);
|
||||
String northing = gpsdir
|
||||
.getString(GpsDirectory.TAG_GPS_LATITUDE_REF);
|
||||
String easting = gpsdir
|
||||
.getString(GpsDirectory.TAG_GPS_LONGITUDE_REF);
|
||||
|
||||
try {
|
||||
alt = gpsdir.getDouble(GpsDirectory.TAG_GPS_ALTITUDE);
|
||||
} catch (Exception ex) {
|
||||
}
|
||||
|
||||
double latsign = 1.0d;
|
||||
if (northing.equalsIgnoreCase("S"))
|
||||
latsign = -1.0d;
|
||||
double lonsign = 1.0d;
|
||||
if (easting.equalsIgnoreCase("W"))
|
||||
lonsign = -1.0d;
|
||||
lat = (Math.abs(latpart[0].doubleValue())
|
||||
+ latpart[1].doubleValue() / 60.0d + latpart[2]
|
||||
.doubleValue() / 3600.0d) * latsign;
|
||||
lon = (Math.abs(lonpart[0].doubleValue())
|
||||
+ lonpart[1].doubleValue() / 60.0d + lonpart[2]
|
||||
.doubleValue() / 3600.0d) * lonsign;
|
||||
|
||||
if (Double.isNaN(lat) || Double.isNaN(lon))
|
||||
error = true;
|
||||
} catch (Exception ex) {
|
||||
error = true;
|
||||
}
|
||||
System.out.println(filename + ": (" + lat + ", " + lon + ")");
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
ImageGeo imageGeo = new ImageGeo(ImageGeo.class.getResource("IMAG0068.jpg").getFile());
|
||||
System.out.println(imageGeo.lon+","+imageGeo.lat);
|
||||
}
|
||||
|
||||
}
|
||||
42
src/main/java/com/nis/util/JsonDateSerializer.java
Normal file
42
src/main/java/com/nis/util/JsonDateSerializer.java
Normal file
@@ -0,0 +1,42 @@
|
||||
/**
|
||||
*@Title: JsonDateSerializer.java
|
||||
*@Package com.nis.domain.restful
|
||||
*@Description TODO
|
||||
*@author dell
|
||||
*@date 2016年9月9日 下午8:36:59
|
||||
*@version 版本号
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.nis.util.DateUtil;
|
||||
|
||||
/**
|
||||
* @ClassName: JsonDateSerializer.java
|
||||
* @Description: TODO 用于非get请求时讲返回结果呈现界面时的Json格式转换,用法 在Date类型的get方法上加上 @JsonSerialize(using=JsonDateSerializer.class)
|
||||
* @author (wx)
|
||||
* @date 2016年9月9日 下午8:36:59
|
||||
* @version V1.0
|
||||
*/
|
||||
public class JsonDateSerializer extends JsonSerializer<Date> {
|
||||
private static final SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",Locale.CHINA);
|
||||
/* (non-Javadoc)
|
||||
* @see com.fasterxml.jackson.databind.JsonSerializer#serialize(java.lang.Object, com.fasterxml.jackson.core.JsonGenerator, com.fasterxml.jackson.databind.SerializerProvider)
|
||||
*/
|
||||
@Override
|
||||
public void serialize(Date date, JsonGenerator gen, SerializerProvider provider)
|
||||
throws IOException, JsonProcessingException {
|
||||
// TODO Auto-generated method stub
|
||||
//gen.writeString(sdf.format(date));
|
||||
gen.writeString(DateUtil.getFormatDate(date, DateUtil.YYYY_MM_DD_HH24_MM_SS));
|
||||
}
|
||||
|
||||
}
|
||||
54
src/main/java/com/nis/util/JsonDateValueProcessor.java
Normal file
54
src/main/java/com/nis/util/JsonDateValueProcessor.java
Normal file
@@ -0,0 +1,54 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.Date;
|
||||
import java.util.Locale;
|
||||
|
||||
import net.sf.json.JsonConfig;
|
||||
import net.sf.json.processors.JsonValueProcessor;
|
||||
|
||||
/**
|
||||
*
|
||||
* @ClassName: JsonDateValueProcessor
|
||||
* @Description: TODO(处理对象中日期类型转换为json时格式问题,后期会删除)
|
||||
* @author (rkg)
|
||||
* @date 2016年9月27日下午3:43:48
|
||||
* @version V1.0
|
||||
*/
|
||||
public class JsonDateValueProcessor implements JsonValueProcessor {
|
||||
private String format = "yyyy-MM-dd'T'HH:mm:ss.SSS";
|
||||
//private String format = "yyyy-MM-dd";
|
||||
|
||||
public JsonDateValueProcessor() {
|
||||
super();
|
||||
}
|
||||
|
||||
public JsonDateValueProcessor(String format) {
|
||||
super();
|
||||
this.format = format;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object processArrayValue(Object parm, JsonConfig arg1) {
|
||||
return process(parm);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object processObjectValue(String key, Object value, JsonConfig arg2) {
|
||||
return process(value);
|
||||
}
|
||||
|
||||
private Object process(Object value) {
|
||||
if (value instanceof Date) {
|
||||
long time= ((Date) value).getTime()-8*60*60*1000;
|
||||
//value=
|
||||
//SimpleDateFormat sdf = new SimpleDateFormat(format, Locale.CHINA);
|
||||
SimpleDateFormat sdf = new SimpleDateFormat(format);
|
||||
return sdf.format(time);
|
||||
|
||||
}
|
||||
return value == null ? "" : value.toString();
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
278
src/main/java/com/nis/util/JsonMapper.java
Normal file
278
src/main/java/com/nis/util/JsonMapper.java
Normal file
@@ -0,0 +1,278 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.TimeZone;
|
||||
|
||||
import org.apache.commons.lang3.StringEscapeUtils;
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonInclude.Include;
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.JsonParser.Feature;
|
||||
import com.fasterxml.jackson.databind.DeserializationFeature;
|
||||
import com.fasterxml.jackson.databind.JavaType;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializationFeature;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||||
import com.fasterxml.jackson.databind.util.JSONPObject;
|
||||
import com.fasterxml.jackson.module.jaxb.JaxbAnnotationModule;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.nis.domain.Page;
|
||||
import com.nis.domain.restful.DfIpPortLog;
|
||||
|
||||
/**
|
||||
* 简单封装Jackson,实现JSON String<->Java Object的Mapper. 封装不同的输出风格,
|
||||
* 使用不同的builder函数创建实例.
|
||||
*
|
||||
* @author ThinkGem
|
||||
* @version 2013-11-15
|
||||
*/
|
||||
public class JsonMapper extends ObjectMapper {
|
||||
|
||||
private static final long serialVersionUID = 1L;
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger(JsonMapper.class);
|
||||
|
||||
private static JsonMapper mapper;
|
||||
|
||||
public JsonMapper() {
|
||||
this(Include.ALWAYS);
|
||||
}
|
||||
|
||||
public JsonMapper(Include include) {
|
||||
// 设置输出时包含属性的风格
|
||||
if (include != null) {
|
||||
this.setSerializationInclusion(include);
|
||||
}
|
||||
// 允许单引号、允许不带引号的字段名称
|
||||
this.enableSimple();
|
||||
// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
|
||||
this.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
|
||||
// 空值
|
||||
/*
|
||||
* this.getSerializerProvider().setNullValueSerializer(new
|
||||
* JsonSerializer<Object>(){
|
||||
*
|
||||
* @Override public void serialize(Object value, JsonGenerator jgen,
|
||||
* SerializerProvider provider) throws IOException,
|
||||
* JsonProcessingException { jgen.writeString(""); } });
|
||||
*/
|
||||
this.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
|
||||
// 进行HTML解码。
|
||||
this.registerModule(new SimpleModule().addSerializer(String.class, new JsonSerializer<String>() {
|
||||
@Override
|
||||
public void serialize(String value, JsonGenerator jgen, SerializerProvider provider)
|
||||
throws IOException, JsonProcessingException {
|
||||
jgen.writeString(StringEscapeUtils.unescapeHtml4(value));
|
||||
}
|
||||
}));
|
||||
// 设置时区
|
||||
this.setTimeZone(TimeZone.getDefault());// getTimeZone("GMT+8:00")
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建只输出非Null且非Empty(如List.isEmpty)的属性到Json字符串的Mapper,建议在外部接口中使用.
|
||||
*/
|
||||
public static JsonMapper getInstance() {
|
||||
if (mapper == null) {
|
||||
mapper = new JsonMapper();// .enableSimple();只输出非Null且非Empty
|
||||
}
|
||||
return mapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建只输出初始值被改变的属性到Json字符串的Mapper, 最节约的存储方式,建议在内部接口中使用。
|
||||
*/
|
||||
public static JsonMapper nonDefaultMapper() {
|
||||
if (mapper == null) {
|
||||
mapper = new JsonMapper(Include.NON_DEFAULT);
|
||||
}
|
||||
return mapper;
|
||||
}
|
||||
|
||||
/**
|
||||
* Object可以是POJO,也可以是Collection或数组。 如果对象为Null, 返回"null". 如果集合为空集合, 返回"[]".
|
||||
*/
|
||||
public String toJson(Object object) {
|
||||
try {
|
||||
return this.writeValueAsString(object);
|
||||
} catch (IOException e) {
|
||||
logger.warn("write to json string error:" + object, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 反序列化POJO或简单Collection如List<String>.
|
||||
*
|
||||
* 如果JSON字符串为Null或"null"字符串, 返回Null. 如果JSON字符串为"[]", 返回空集合.
|
||||
*
|
||||
* 如需反序列化复杂Collection如List<MyBean>, 请使用fromJson(String,JavaType)
|
||||
*
|
||||
* @see #fromJson(String, JavaType)
|
||||
*/
|
||||
public <T> T fromJson(String jsonString, Class<T> clazz) {
|
||||
if (StringUtils.isEmpty(jsonString)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return this.readValue(jsonString, clazz);
|
||||
} catch (IOException e) {
|
||||
logger.warn("parse json string error:" + jsonString, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 反序列化复杂Collection如List<Bean>, 先使用函數createCollectionType构造类型,然后调用本函数.
|
||||
*
|
||||
* @see #createCollectionType(Class, Class...)
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T fromJson(String jsonString, JavaType javaType) {
|
||||
if (StringUtils.isEmpty(jsonString)) {
|
||||
return null;
|
||||
}
|
||||
try {
|
||||
return (T) this.readValue(jsonString, javaType);
|
||||
} catch (IOException e) {
|
||||
logger.warn("parse json string error:" + jsonString, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 構造泛型的Collection Type如: ArrayList<MyBean>,
|
||||
* 则调用constructCollectionType(ArrayList.class,MyBean.class)
|
||||
* HashMap<String,MyBean>, 则调用(HashMap.class,String.class, MyBean.class)
|
||||
*/
|
||||
public JavaType createCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
|
||||
return this.getTypeFactory().constructParametricType(collectionClass, elementClasses);
|
||||
}
|
||||
|
||||
/**
|
||||
* 當JSON裡只含有Bean的部分屬性時,更新一個已存在Bean,只覆蓋該部分的屬性.
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public <T> T update(String jsonString, T object) {
|
||||
try {
|
||||
return (T) this.readerForUpdating(object).readValue(jsonString);
|
||||
} catch (JsonProcessingException e) {
|
||||
logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
|
||||
} catch (IOException e) {
|
||||
logger.warn("update json string:" + jsonString + " to object:" + object + " error.", e);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 輸出JSONP格式數據.
|
||||
*/
|
||||
public String toJsonP(String functionName, Object object) {
|
||||
return toJson(new JSONPObject(functionName, object));
|
||||
}
|
||||
|
||||
/**
|
||||
* 設定是否使用Enum的toString函數來讀寫Enum, 為False時時使用Enum的name()函數來讀寫Enum, 默認為False.
|
||||
* 注意本函數一定要在Mapper創建後, 所有的讀寫動作之前調用.
|
||||
*/
|
||||
public JsonMapper enableEnumUseToString() {
|
||||
this.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING);
|
||||
this.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 支持使用Jaxb的Annotation,使得POJO上的annotation不用与Jackson耦合。
|
||||
* 默认会先查找jaxb的annotation,如果找不到再找jackson的。
|
||||
*/
|
||||
public JsonMapper enableJaxbAnnotation() {
|
||||
JaxbAnnotationModule module = new JaxbAnnotationModule();
|
||||
this.registerModule(module);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 允许单引号 允许不带引号的字段名称
|
||||
*/
|
||||
public JsonMapper enableSimple() {
|
||||
this.configure(Feature.ALLOW_SINGLE_QUOTES, true);
|
||||
this.configure(Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 取出Mapper做进一步的设置或使用其他序列化API.
|
||||
*/
|
||||
public ObjectMapper getMapper() {
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 对象转换为JSON字符串
|
||||
*
|
||||
* @param object
|
||||
* @return
|
||||
*/
|
||||
public static String toJsonString(Object object) {
|
||||
return JsonMapper.getInstance().toJson(object);
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON字符串转换为对象
|
||||
*
|
||||
* @param jsonString
|
||||
* @param clazz
|
||||
* @return
|
||||
*/
|
||||
public static Object fromJsonString(String jsonString, Class<?> clazz) {
|
||||
return JsonMapper.getInstance().fromJson(jsonString, clazz);
|
||||
}
|
||||
|
||||
/**
|
||||
* JSON字符串转换为对象
|
||||
*
|
||||
* @param jsonString
|
||||
* @param clazz
|
||||
* @return
|
||||
*/
|
||||
public static Object fromJsonList(String jsonString, Class<?> clazz) {
|
||||
JavaType javaType = JsonMapper.getInstance().createCollectionType(ArrayList.class, clazz);
|
||||
return JsonMapper.getInstance().fromJson(jsonString,javaType );
|
||||
}
|
||||
/**
|
||||
* 测试
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
/*
|
||||
* List<Map<String, Object>> list = Lists.newArrayList(); Map<String,
|
||||
* Object> map = Maps.newHashMap(); map.put("id", 1); map.put("pId",
|
||||
* -1); map.put("name", "根节点"); list.add(map); map = Maps.newHashMap();
|
||||
* map.put("id", 2); map.put("pId", 1); map.put("name", "你好");
|
||||
* map.put("open", true); list.add(map);
|
||||
*/
|
||||
List<DfIpPortLog> ipPort = new ArrayList<DfIpPortLog>();
|
||||
DfIpPortLog ip = new DfIpPortLog();
|
||||
ip.setCljIp("aa");
|
||||
ip.setId(null);
|
||||
ipPort.add(ip);
|
||||
Page page = new Page();
|
||||
page.setList(ipPort);
|
||||
String json = JsonMapper.getInstance().toJsonString(ipPort);
|
||||
System.out.println(json);
|
||||
}
|
||||
|
||||
}
|
||||
192
src/main/java/com/nis/util/LogUtils.java
Normal file
192
src/main/java/com/nis/util/LogUtils.java
Normal file
@@ -0,0 +1,192 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.apache.shiro.authz.annotation.RequiresPermissions;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.google.common.collect.Maps;
|
||||
import com.nis.domain.SysDataDictionaryItem;
|
||||
import com.nis.domain.SysLog;
|
||||
import com.nis.domain.SysMenu;
|
||||
import com.nis.domain.SysUser;
|
||||
import com.nis.web.dao.SysLogDao;
|
||||
import com.nis.web.dao.SysMenuDao;
|
||||
import com.nis.web.security.UserUtils;
|
||||
import com.nis.web.service.SpringContextHolder;
|
||||
import com.sun.corba.se.impl.orbutil.closure.Constant;
|
||||
|
||||
|
||||
public class LogUtils {
|
||||
|
||||
public static final String CACHE_MENU_NAME_PATH_MAP = "menuNamePathMap";
|
||||
|
||||
private static SysLogDao logDao = SpringContextHolder.getBean(SysLogDao.class);
|
||||
private static SysMenuDao menuDao = SpringContextHolder.getBean(SysMenuDao.class);
|
||||
|
||||
/**
|
||||
* 保存日志
|
||||
*/
|
||||
public static void saveLog(HttpServletRequest request, String title){
|
||||
saveLog(request, null, null, title, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存日志
|
||||
*/
|
||||
public static void saveLog(HttpServletRequest request, Object handler, Exception ex, String title){
|
||||
saveLog(request, handler, ex, title, 0);
|
||||
}
|
||||
|
||||
public static void saveLog(HttpServletRequest request, Object handler, Exception ex, String title, long consumerTime){
|
||||
SysUser user = UserUtils.getUser();
|
||||
if (user != null && user.getId() != null){
|
||||
SysLog log = new SysLog();
|
||||
log.setType(getOperateType(handler));
|
||||
log.setTitle(title);
|
||||
log.setConsumerTime(consumerTime);
|
||||
log.setState(ex == null ? Constants.LOG_ACCESS_SUCCESS : Constants.LOG_ACCESS_EXCEPTION);
|
||||
log.setRemoteAddr(StringUtils.getRemoteAddr(request));
|
||||
log.setUserAgent(request.getHeader("user-agent"));
|
||||
log.setRequestUri(request.getRequestURI());
|
||||
log.setParams(request.getParameterMap());
|
||||
log.setMethod(request.getMethod());
|
||||
log.setCreateBy(user.getName());
|
||||
log.setCreateDate(new Date());
|
||||
// 异步保存日志
|
||||
new SaveLogThread(log, handler, ex).start();
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 保存日志线程
|
||||
*/
|
||||
public static class SaveLogThread extends Thread{
|
||||
|
||||
private SysLog log;
|
||||
private Object handler;
|
||||
private Exception ex;
|
||||
|
||||
public SaveLogThread(SysLog log, Object handler, Exception ex){
|
||||
super(SaveLogThread.class.getSimpleName());
|
||||
this.log = log;
|
||||
this.handler = handler;
|
||||
this.ex = ex;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
// 获取日志标题
|
||||
if (StringUtils.isBlank(log.getTitle())){
|
||||
String permission = "";
|
||||
if (handler instanceof HandlerMethod){
|
||||
Method m = ((HandlerMethod)handler).getMethod();
|
||||
RequiresPermissions rp = m.getAnnotation(RequiresPermissions.class);
|
||||
permission = (rp != null ? StringUtils.join(rp.value(), ",") : "");
|
||||
}
|
||||
log.setTitle(getMenuNamePath(log.getRequestUri(), permission));
|
||||
}
|
||||
// 如果有异常,设置异常信息
|
||||
log.setException(Exceptions.getStackTraceAsString(ex));
|
||||
// 如果无标题并无异常日志,则不保存信息
|
||||
if (StringUtils.isBlank(log.getTitle()) && StringUtils.isBlank(log.getException())){
|
||||
return;
|
||||
}
|
||||
// 保存日志信息
|
||||
logDao.insert(log);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
public static int getOperateType(Object handler) {
|
||||
int type = Constants.DEFAULT_METHOD_TYPE;
|
||||
|
||||
if (!StringUtil.isEmpty(handler)) {
|
||||
if (handler instanceof HandlerMethod) {
|
||||
Method m = ((HandlerMethod)handler).getMethod();
|
||||
String methodName = m.getName();
|
||||
List<SysDataDictionaryItem> dictList = DictUtils.getDictList("SYS_LOG_TYPE");
|
||||
for(SysDataDictionaryItem sysDataDictionaryItem:dictList){
|
||||
if(methodName.toLowerCase().matches(sysDataDictionaryItem.getItemCode().toLowerCase()+".*")){
|
||||
type = Integer.parseInt(sysDataDictionaryItem.getItemValue());
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
|
||||
return type;
|
||||
}
|
||||
|
||||
|
||||
|
||||
/**
|
||||
* 获取菜单名称路径(如:系统设置-机构用户-用户管理-编辑)
|
||||
*/
|
||||
public static String getMenuNamePath(String requestUri, String permission){
|
||||
String href = StringUtils.substringAfter(requestUri, Configurations.getStringProperty("adminPath", "/nis"));
|
||||
@SuppressWarnings("unchecked")
|
||||
Map<String, String> menuMap = (Map<String, String>)CacheUtils.get(CACHE_MENU_NAME_PATH_MAP);
|
||||
if (menuMap == null){
|
||||
menuMap = Maps.newHashMap();
|
||||
List<SysMenu> menuList = menuDao.findAllList(new SysMenu());
|
||||
for (SysMenu menu : menuList){
|
||||
// 获取菜单名称路径(如:系统设置-机构用户-用户管理-编辑)
|
||||
String namePath = "";
|
||||
if (menu.getParentIds() != null){
|
||||
List<String> namePathList = Lists.newArrayList();
|
||||
for (String id : StringUtils.split(menu.getParentIds(), ",")){
|
||||
|
||||
|
||||
if (SysMenu.getRootId().equals(Long.valueOf(id))){
|
||||
continue; // 过滤跟节点
|
||||
}
|
||||
for (SysMenu m : menuList){
|
||||
if (m.getId().equals(Long.valueOf(id))){
|
||||
namePathList.add(m.getName());
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
namePathList.add(menu.getName());
|
||||
namePath = StringUtils.join(namePathList, "-");
|
||||
}
|
||||
// 设置菜单名称路径
|
||||
if (StringUtils.isNotBlank(menu.getHref())){
|
||||
menuMap.put(menu.getHref(), namePath);
|
||||
}else if (StringUtils.isNotBlank(menu.getPermission())){
|
||||
for (String p : StringUtils.split(menu.getPermission())){
|
||||
menuMap.put(p, namePath);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
CacheUtils.put(CACHE_MENU_NAME_PATH_MAP, menuMap);
|
||||
}
|
||||
String menuNamePath = menuMap.get(href);
|
||||
if (menuNamePath == null){
|
||||
for (String p : StringUtils.split(permission)){
|
||||
menuNamePath = menuMap.get(p);
|
||||
if (StringUtils.isNotBlank(menuNamePath)){
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (menuNamePath == null){
|
||||
return "";
|
||||
}
|
||||
}
|
||||
return menuNamePath;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
83
src/main/java/com/nis/util/MD5Utils.java
Normal file
83
src/main/java/com/nis/util/MD5Utils.java
Normal file
@@ -0,0 +1,83 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.NoSuchAlgorithmException;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.apache.commons.lang3.StringEscapeUtils;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
import org.springframework.web.servlet.LocaleResolver;
|
||||
|
||||
import com.ckfinder.connector.ServletContextFactory;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.nis.web.service.SpringContextHolder;
|
||||
|
||||
/**
|
||||
* 字符串工具类, 继承org.apache.commons.lang3.StringUtils类
|
||||
* @author ThinkGem
|
||||
* @version 2013-05-22
|
||||
*/
|
||||
public class MD5Utils{
|
||||
|
||||
/**
|
||||
* 字符串转为MD532位小写
|
||||
* @param plain
|
||||
* @return
|
||||
*/
|
||||
public static String md5LowerCase(String plain) throws Exception{
|
||||
String re_md5 = new String();
|
||||
MessageDigest md = MessageDigest.getInstance("MD5");
|
||||
md.update(plain.getBytes());
|
||||
byte b[] = md.digest();
|
||||
|
||||
int i;
|
||||
|
||||
StringBuffer buf = new StringBuffer("");
|
||||
for (int offset = 0; offset < b.length; offset++) {
|
||||
i = b[offset];
|
||||
if (i < 0)
|
||||
i += 256;
|
||||
if (i < 16)
|
||||
buf.append("0");
|
||||
buf.append(Integer.toHexString(i));
|
||||
}
|
||||
|
||||
re_md5 = buf.toString();
|
||||
return re_md5;
|
||||
}
|
||||
public static byte[] createChecksum(String filename) throws IOException, NoSuchAlgorithmException{
|
||||
InputStream fis=new FileInputStream(filename);
|
||||
byte[] buffer=new byte[1024];
|
||||
MessageDigest complete=MessageDigest.getInstance("MD5");
|
||||
int numRead;
|
||||
do{
|
||||
numRead=fis.read(buffer);
|
||||
if(numRead>0){
|
||||
complete.update(buffer,0,numRead);
|
||||
}
|
||||
}while(numRead!=-1);
|
||||
fis.close();
|
||||
return complete.digest();
|
||||
}
|
||||
public static String getMD5Checksum(String filename) throws NoSuchAlgorithmException, IOException{
|
||||
byte[] b=createChecksum(filename);
|
||||
StringBuffer result=new StringBuffer();
|
||||
for(int i=0;i<b.length;i++){
|
||||
result.append(Integer.toString((b[i] & 0xff)+ 0x100,16).substring(1));
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
}
|
||||
88
src/main/java/com/nis/util/ObjectUtils.java
Normal file
88
src/main/java/com/nis/util/ObjectUtils.java
Normal file
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.io.ByteArrayInputStream;
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.io.ObjectInputStream;
|
||||
import java.io.ObjectOutputStream;
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
|
||||
/**
|
||||
* 对象操作工具类, 继承org.apache.commons.lang3.ObjectUtils类
|
||||
* @author ThinkGem
|
||||
* @version 2014-6-29
|
||||
*/
|
||||
public class ObjectUtils extends org.apache.commons.lang3.ObjectUtils {
|
||||
|
||||
/**
|
||||
* 注解到对象复制,只复制能匹配上的方法。
|
||||
* @param annotation
|
||||
* @param object
|
||||
*/
|
||||
public static void annotationToObject(Object annotation, Object object){
|
||||
if (annotation != null){
|
||||
Class<?> annotationClass = annotation.getClass();
|
||||
Class<?> objectClass = object.getClass();
|
||||
for (Method m : objectClass.getMethods()){
|
||||
if (StringUtils.startsWith(m.getName(), "set")){
|
||||
try {
|
||||
String s = StringUtils.uncapitalize(StringUtils.substring(m.getName(), 3));
|
||||
Object obj = annotationClass.getMethod(s).invoke(annotation);
|
||||
if (obj != null && !"".equals(obj.toString())){
|
||||
if (object == null){
|
||||
object = objectClass.newInstance();
|
||||
}
|
||||
m.invoke(object, obj);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// 忽略所有设置失败方法
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 序列化对象
|
||||
* @param object
|
||||
* @return
|
||||
*/
|
||||
public static byte[] serialize(Object object) {
|
||||
ObjectOutputStream oos = null;
|
||||
ByteArrayOutputStream baos = null;
|
||||
try {
|
||||
if (object != null){
|
||||
baos = new ByteArrayOutputStream();
|
||||
oos = new ObjectOutputStream(baos);
|
||||
oos.writeObject(object);
|
||||
return baos.toByteArray();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 反序列化对象
|
||||
* @param bytes
|
||||
* @return
|
||||
*/
|
||||
public static Object unserialize(byte[] bytes) {
|
||||
ByteArrayInputStream bais = null;
|
||||
try {
|
||||
if (bytes != null && bytes.length > 0){
|
||||
bais = new ByteArrayInputStream(bytes);
|
||||
ObjectInputStream ois = new ObjectInputStream(bais);
|
||||
return ois.readObject();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
97
src/main/java/com/nis/util/OracleErrorCodeUtil.java
Normal file
97
src/main/java/com/nis/util/OracleErrorCodeUtil.java
Normal file
@@ -0,0 +1,97 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
import com.nis.restful.RestBusinessCode;
|
||||
import com.nis.restful.RestServiceException;
|
||||
import com.nis.web.service.SaveRequestLogThread;
|
||||
|
||||
public class OracleErrorCodeUtil {
|
||||
/**
|
||||
* 返回异常信息内容
|
||||
*
|
||||
* @param e
|
||||
* @return
|
||||
*/
|
||||
public static String getOraCode(Exception e) {
|
||||
if (e == null) {
|
||||
return "";
|
||||
}
|
||||
|
||||
String errorMessage = e.getMessage();
|
||||
if (null != errorMessage && errorMessage.length() > 0) {
|
||||
int index = errorMessage.toUpperCase().indexOf("ORA-");
|
||||
if (index != -1) {
|
||||
return errorMessage.substring(index + 4, index + 9);
|
||||
|
||||
}
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据错误码抛出对应的异常,case内容为空的时候会按照下个case的异常内容来抛出异常,修改时请注意
|
||||
*/
|
||||
|
||||
public static void throwExceptionInfo(SaveRequestLogThread thread, long time, String errorCode) {
|
||||
|
||||
switch (errorCode) {
|
||||
|
||||
case "00001":
|
||||
throw new RestServiceException(thread, time, "数据库对应的id已经存在!",
|
||||
RestBusinessCode.insert_data_repeat.getValue());
|
||||
case "00942":
|
||||
case "00903":
|
||||
throw new RestServiceException(thread, time, "数据库中未找到对应的表!",
|
||||
RestBusinessCode.param_formate_error.getValue());
|
||||
case "01401":
|
||||
case "12899":
|
||||
throw new RestServiceException(thread, time, "数据长度大于规定长度!",
|
||||
RestBusinessCode.param_formate_error.getValue());
|
||||
case "01400":
|
||||
case "01407":
|
||||
throw new RestServiceException(thread, time, "必须数据不能为空或数据不完整!",
|
||||
RestBusinessCode.param_formate_error.getValue());
|
||||
case "01722":
|
||||
throw new RestServiceException(thread, time, "无效的数字!", RestBusinessCode.param_formate_error.getValue());
|
||||
case "01465":
|
||||
throw new RestServiceException(thread, time, "无效的十六进制数字!", RestBusinessCode.param_formate_error.getValue());
|
||||
default:
|
||||
throw new RestServiceException(thread, time, "数据操作发生异常!", RestBusinessCode.unknow_error.getValue());
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static Map<Integer, String> throwExceptionInfo(String errorCode) {
|
||||
Map<Integer, String> map = new HashMap<Integer, String>();
|
||||
switch (errorCode) {
|
||||
case "00001":
|
||||
map.put(RestBusinessCode.insert_data_repeat.getValue(), "数据库对应的id已经存在!");
|
||||
return map;
|
||||
case "00942":
|
||||
case "00903":
|
||||
map.put(RestBusinessCode.param_formate_error.getValue(), "数据库中未找到对应的表!");
|
||||
return map;
|
||||
case "01401":
|
||||
case "12899":
|
||||
map.put(RestBusinessCode.param_formate_error.getValue(), "数据长度大于规定长度!");
|
||||
return map;
|
||||
case "01400":
|
||||
case "01407":
|
||||
map.put(RestBusinessCode.param_formate_error.getValue(), "必须数据不能为空或数据不完整!");
|
||||
return map;
|
||||
case "01722":
|
||||
map.put(RestBusinessCode.param_formate_error.getValue(), "无效的数字!");
|
||||
return map;
|
||||
case "01465":
|
||||
map.put(RestBusinessCode.param_formate_error.getValue(), "无效的十六进制数字!");
|
||||
return map;
|
||||
default:
|
||||
map.put(RestBusinessCode.unknow_error.getValue(), "数据操作发生异常!");
|
||||
return map;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.util.Properties;
|
||||
|
||||
import org.apache.commons.codec.binary.Base64;
|
||||
import org.springframework.beans.BeansException;
|
||||
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
|
||||
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
|
||||
|
||||
import com.nis.crypt.AESUtil;
|
||||
|
||||
public class PropertyPlaceholderConfigurerCrypt extends PropertyPlaceholderConfigurer {
|
||||
|
||||
@Override
|
||||
protected void processProperties(ConfigurableListableBeanFactory beanFactoryToProcess, Properties props)
|
||||
throws BeansException {
|
||||
|
||||
try {
|
||||
String productPassword = props.getProperty("jdbc.product.password");
|
||||
String productScretKey = props.getProperty("jdbc.product.key");
|
||||
if (null != productPassword) {
|
||||
props.setProperty("jdbc.product.password",
|
||||
new String(AESUtil.decrypt(Base64.decodeBase64(productPassword), productScretKey)));
|
||||
}
|
||||
|
||||
String devlopPassword = props.getProperty("jdbc.devlop.password");
|
||||
String devlopScretKey = props.getProperty("jdbc.devlop.key");
|
||||
if (null != devlopPassword) {
|
||||
props.setProperty("jdbc.devlop.password",
|
||||
new String(AESUtil.decrypt(Base64.decodeBase64(devlopPassword), devlopScretKey)));
|
||||
}
|
||||
|
||||
String logPassword = props.getProperty("jdbc.log.password");
|
||||
String logScretKey = props.getProperty("jdbc.log.key");
|
||||
if (null != logPassword) {
|
||||
props.setProperty("jdbc.log.password",
|
||||
new String(AESUtil.decrypt(Base64.decodeBase64(logPassword), logScretKey)));
|
||||
}
|
||||
|
||||
// 日志A版
|
||||
String logAPassword = props.getProperty("jdbc.logA.password");
|
||||
String logAScretKey = props.getProperty("jdbc.logA.key");
|
||||
if (null != logAPassword) {
|
||||
props.setProperty("jdbc.logA.password",
|
||||
new String(AESUtil.decrypt(Base64.decodeBase64(logAPassword), logAScretKey)));
|
||||
}
|
||||
// 日志A版
|
||||
String logCPassword = props.getProperty("jdbc.logC.password");
|
||||
String logCScretKey = props.getProperty("jdbc.logC.key");
|
||||
if (null != logAPassword) {
|
||||
props.setProperty("jdbc.logC.password",
|
||||
new String(AESUtil.decrypt(Base64.decodeBase64(logCPassword), logCScretKey)));
|
||||
}
|
||||
|
||||
|
||||
// 测试使用,后期会删除
|
||||
String testPassword = props.getProperty("jdbc.test.password");
|
||||
String testScretKey = props.getProperty("jdbc.test.key");
|
||||
if (null != testPassword) {
|
||||
props.setProperty("jdbc.test.password",
|
||||
new String(AESUtil.decrypt(Base64.decodeBase64(testPassword), testScretKey)));
|
||||
}
|
||||
|
||||
String jkPzPassword = props.getProperty("jdbc.jk.password");
|
||||
String jkPzScretKey = props.getProperty("jdbc.jk.key");
|
||||
if (null != jkPzPassword) {
|
||||
props.setProperty("jdbc.jk.password",
|
||||
new String(AESUtil.decrypt(Base64.decodeBase64(jkPzPassword), jkPzScretKey)));
|
||||
}
|
||||
//A版hive库
|
||||
String hiveAPassword = props.getProperty("jdbc.hiveA.password");
|
||||
String hiveAScretKey = props.getProperty("jdbc.hiveA.key");
|
||||
if (null != hiveAPassword) {
|
||||
props.setProperty("jdbc.hiveA.password",
|
||||
new String(AESUtil.decrypt(Base64.decodeBase64(hiveAPassword), hiveAScretKey)));
|
||||
}
|
||||
|
||||
//B版hive库
|
||||
String hiveBPassword = props.getProperty("jdbc.hiveB.password");
|
||||
String hiveBScretKey = props.getProperty("jdbc.hiveB.key");
|
||||
if (null != hiveBPassword) {
|
||||
props.setProperty("jdbc.hiveB.password",
|
||||
new String(AESUtil.decrypt(Base64.decodeBase64(hiveBPassword), hiveBScretKey)));
|
||||
}
|
||||
|
||||
//神通数据库库
|
||||
String clusterPassword = props.getProperty("jdbc.log.cluster.password");
|
||||
String clusterScretKey = props.getProperty("jdbc.log.cluster.key");
|
||||
if (null != clusterPassword) {
|
||||
props.setProperty("jdbc.log.cluster.password",
|
||||
new String(AESUtil.decrypt(Base64.decodeBase64(clusterPassword), clusterScretKey)));
|
||||
}
|
||||
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
super.processProperties(beanFactoryToProcess, props);
|
||||
}
|
||||
|
||||
}
|
||||
304
src/main/java/com/nis/util/Reflections.java
Normal file
304
src/main/java/com/nis/util/Reflections.java
Normal file
@@ -0,0 +1,304 @@
|
||||
/**
|
||||
* Copyright (c) 2005-2012 springside.org.cn
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.lang.reflect.Method;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.lang.reflect.ParameterizedType;
|
||||
import java.lang.reflect.Type;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.commons.lang3.Validate;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.util.Assert;
|
||||
|
||||
/**
|
||||
* 反射工具类.
|
||||
* 提供调用getter/setter方法, 访问私有变量, 调用私有方法, 获取泛型类型Class, 被AOP过的真实类等工具函数.
|
||||
* @author calvin
|
||||
* @version 2013-01-15
|
||||
*/
|
||||
@SuppressWarnings("rawtypes")
|
||||
public class Reflections {
|
||||
|
||||
private static final String SETTER_PREFIX = "set";
|
||||
|
||||
private static final String GETTER_PREFIX = "get";
|
||||
|
||||
private static final String CGLIB_CLASS_SEPARATOR = "$$";
|
||||
|
||||
private static Logger logger = LoggerFactory.getLogger(Reflections.class);
|
||||
|
||||
/**
|
||||
* 调用Getter方法.
|
||||
* 支持多级,如:对象名.对象名.方法
|
||||
*/
|
||||
public static Object invokeGetter(Object obj, String propertyName) {
|
||||
Object object = obj;
|
||||
for (String name : StringUtils.split(propertyName, ".")){
|
||||
String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(name);
|
||||
object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {});
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
/**
|
||||
* 调用Setter方法, 仅匹配方法名。
|
||||
* 支持多级,如:对象名.对象名.方法
|
||||
*/
|
||||
public static void invokeSetter(Object obj, String propertyName, Object value) {
|
||||
Object object = obj;
|
||||
String[] names = StringUtils.split(propertyName, ".");
|
||||
for (int i=0; i<names.length; i++){
|
||||
if(i<names.length-1){
|
||||
String getterMethodName = GETTER_PREFIX + StringUtils.capitalize(names[i]);
|
||||
object = invokeMethod(object, getterMethodName, new Class[] {}, new Object[] {});
|
||||
}else{
|
||||
String setterMethodName = SETTER_PREFIX + StringUtils.capitalize(names[i]);
|
||||
invokeMethodByName(object, setterMethodName, new Object[] { value });
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接读取对象属性值, 无视private/protected修饰符, 不经过getter函数.
|
||||
*/
|
||||
public static Object getFieldValue(final Object obj, final String fieldName) {
|
||||
Field field = getAccessibleField(obj, fieldName);
|
||||
|
||||
if (field == null) {
|
||||
throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
|
||||
}
|
||||
|
||||
Object result = null;
|
||||
try {
|
||||
result = field.get(obj);
|
||||
} catch (IllegalAccessException e) {
|
||||
logger.error("不可能抛出的异常{}", e.getMessage());
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接设置对象属性值, 无视private/protected修饰符, 不经过setter函数.
|
||||
*/
|
||||
public static void setFieldValue(final Object obj, final String fieldName, final Object value) {
|
||||
Field field = getAccessibleField(obj, fieldName);
|
||||
|
||||
if (field == null) {
|
||||
throw new IllegalArgumentException("Could not find field [" + fieldName + "] on target [" + obj + "]");
|
||||
}
|
||||
|
||||
try {
|
||||
field.set(obj, value);
|
||||
} catch (IllegalAccessException e) {
|
||||
logger.error("不可能抛出的异常:{}", e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接调用对象方法, 无视private/protected修饰符.
|
||||
* 用于一次性调用的情况,否则应使用getAccessibleMethod()函数获得Method后反复调用.
|
||||
* 同时匹配方法名+参数类型,
|
||||
*/
|
||||
public static Object invokeMethod(final Object obj, final String methodName, final Class<?>[] parameterTypes,
|
||||
final Object[] args) {
|
||||
Method method = getAccessibleMethod(obj, methodName, parameterTypes);
|
||||
if (method == null) {
|
||||
throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
|
||||
}
|
||||
|
||||
try {
|
||||
return method.invoke(obj, args);
|
||||
} catch (Exception e) {
|
||||
throw convertReflectionExceptionToUnchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 直接调用对象方法, 无视private/protected修饰符,
|
||||
* 用于一次性调用的情况,否则应使用getAccessibleMethodByName()函数获得Method后反复调用.
|
||||
* 只匹配函数名,如果有多个同名函数调用第一个。
|
||||
*/
|
||||
public static Object invokeMethodByName(final Object obj, final String methodName, final Object[] args) {
|
||||
Method method = getAccessibleMethodByName(obj, methodName);
|
||||
if (method == null) {
|
||||
throw new IllegalArgumentException("Could not find method [" + methodName + "] on target [" + obj + "]");
|
||||
}
|
||||
|
||||
try {
|
||||
return method.invoke(obj, args);
|
||||
} catch (Exception e) {
|
||||
throw convertReflectionExceptionToUnchecked(e);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 循环向上转型, 获取对象的DeclaredField, 并强制设置为可访问.
|
||||
*
|
||||
* 如向上转型到Object仍无法找到, 返回null.
|
||||
*/
|
||||
public static Field getAccessibleField(final Object obj, final String fieldName) {
|
||||
Validate.notNull(obj, "object can't be null");
|
||||
Validate.notBlank(fieldName, "fieldName can't be blank");
|
||||
for (Class<?> superClass = obj.getClass(); superClass != Object.class; superClass = superClass.getSuperclass()) {
|
||||
try {
|
||||
Field field = superClass.getDeclaredField(fieldName);
|
||||
makeAccessible(field);
|
||||
return field;
|
||||
} catch (NoSuchFieldException e) {//NOSONAR
|
||||
// Field不在当前类定义,继续向上转型
|
||||
continue;// new add
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
|
||||
* 如向上转型到Object仍无法找到, 返回null.
|
||||
* 匹配函数名+参数类型。
|
||||
*
|
||||
* 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
|
||||
*/
|
||||
public static Method getAccessibleMethod(final Object obj, final String methodName,
|
||||
final Class<?>... parameterTypes) {
|
||||
Validate.notNull(obj, "object can't be null");
|
||||
Validate.notBlank(methodName, "methodName can't be blank");
|
||||
|
||||
for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
|
||||
try {
|
||||
Method method = searchType.getDeclaredMethod(methodName, parameterTypes);
|
||||
makeAccessible(method);
|
||||
return method;
|
||||
} catch (NoSuchMethodException e) {
|
||||
// Method不在当前类定义,继续向上转型
|
||||
continue;// new add
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 循环向上转型, 获取对象的DeclaredMethod,并强制设置为可访问.
|
||||
* 如向上转型到Object仍无法找到, 返回null.
|
||||
* 只匹配函数名。
|
||||
*
|
||||
* 用于方法需要被多次调用的情况. 先使用本函数先取得Method,然后调用Method.invoke(Object obj, Object... args)
|
||||
*/
|
||||
public static Method getAccessibleMethodByName(final Object obj, final String methodName) {
|
||||
Validate.notNull(obj, "object can't be null");
|
||||
Validate.notBlank(methodName, "methodName can't be blank");
|
||||
|
||||
for (Class<?> searchType = obj.getClass(); searchType != Object.class; searchType = searchType.getSuperclass()) {
|
||||
Method[] methods = searchType.getDeclaredMethods();
|
||||
for (Method method : methods) {
|
||||
if (method.getName().equals(methodName)) {
|
||||
makeAccessible(method);
|
||||
return method;
|
||||
}
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 改变private/protected的方法为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
|
||||
*/
|
||||
public static void makeAccessible(Method method) {
|
||||
if ((!Modifier.isPublic(method.getModifiers()) || !Modifier.isPublic(method.getDeclaringClass().getModifiers()))
|
||||
&& !method.isAccessible()) {
|
||||
method.setAccessible(true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 改变private/protected的成员变量为public,尽量不调用实际改动的语句,避免JDK的SecurityManager抱怨。
|
||||
*/
|
||||
public static void makeAccessible(Field field) {
|
||||
if ((!Modifier.isPublic(field.getModifiers()) || !Modifier.isPublic(field.getDeclaringClass().getModifiers()) || Modifier
|
||||
.isFinal(field.getModifiers())) && !field.isAccessible()) {
|
||||
field.setAccessible(true);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过反射, 获得Class定义中声明的泛型参数的类型, 注意泛型必须定义在父类处
|
||||
* 如无法找到, 返回Object.class.
|
||||
* eg.
|
||||
* public UserDao extends HibernateDao<User>
|
||||
*
|
||||
* @param clazz The class to introspect
|
||||
* @return the first generic declaration, or Object.class if cannot be determined
|
||||
*/
|
||||
@SuppressWarnings("unchecked")
|
||||
public static <T> Class<T> getClassGenricType(final Class clazz) {
|
||||
return getClassGenricType(clazz, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 通过反射, 获得Class定义中声明的父类的泛型参数的类型.
|
||||
* 如无法找到, 返回Object.class.
|
||||
*
|
||||
* 如public UserDao extends HibernateDao<User,Long>
|
||||
*
|
||||
* @param clazz clazz The class to introspect
|
||||
* @param index the Index of the generic ddeclaration,start from 0.
|
||||
* @return the index generic declaration, or Object.class if cannot be determined
|
||||
*/
|
||||
public static Class getClassGenricType(final Class clazz, final int index) {
|
||||
|
||||
Type genType = clazz.getGenericSuperclass();
|
||||
|
||||
if (!(genType instanceof ParameterizedType)) {
|
||||
logger.warn(clazz.getSimpleName() + "'s superclass not ParameterizedType");
|
||||
return Object.class;
|
||||
}
|
||||
|
||||
Type[] params = ((ParameterizedType) genType).getActualTypeArguments();
|
||||
|
||||
if (index >= params.length || index < 0) {
|
||||
logger.warn("Index: " + index + ", Size of " + clazz.getSimpleName() + "'s Parameterized Type: "
|
||||
+ params.length);
|
||||
return Object.class;
|
||||
}
|
||||
if (!(params[index] instanceof Class)) {
|
||||
logger.warn(clazz.getSimpleName() + " not set the actual class on superclass generic parameter");
|
||||
return Object.class;
|
||||
}
|
||||
|
||||
return (Class) params[index];
|
||||
}
|
||||
|
||||
public static Class<?> getUserClass(Object instance) {
|
||||
Assert.notNull(instance, "Instance must not be null");
|
||||
Class clazz = instance.getClass();
|
||||
if (clazz != null && clazz.getName().contains(CGLIB_CLASS_SEPARATOR)) {
|
||||
Class<?> superClass = clazz.getSuperclass();
|
||||
if (superClass != null && !Object.class.equals(superClass)) {
|
||||
return superClass;
|
||||
}
|
||||
}
|
||||
return clazz;
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* 将反射时的checked exception转换为unchecked exception.
|
||||
*/
|
||||
public static RuntimeException convertReflectionExceptionToUnchecked(Exception e) {
|
||||
if (e instanceof IllegalAccessException || e instanceof IllegalArgumentException
|
||||
|| e instanceof NoSuchMethodException) {
|
||||
return new IllegalArgumentException(e);
|
||||
} else if (e instanceof InvocationTargetException) {
|
||||
return new RuntimeException(((InvocationTargetException) e).getTargetException());
|
||||
} else if (e instanceof RuntimeException) {
|
||||
return (RuntimeException) e;
|
||||
}
|
||||
return new RuntimeException("Unexpected Checked Exception.", e);
|
||||
}
|
||||
}
|
||||
475
src/main/java/com/nis/util/StringUtils.java
Normal file
475
src/main/java/com/nis/util/StringUtils.java
Normal file
@@ -0,0 +1,475 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.util;
|
||||
|
||||
import java.io.UnsupportedEncodingException;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.regex.Matcher;
|
||||
import java.util.regex.Pattern;
|
||||
|
||||
import javax.servlet.http.HttpServletRequest;
|
||||
|
||||
import org.apache.commons.lang3.StringEscapeUtils;
|
||||
import org.springframework.web.context.request.RequestContextHolder;
|
||||
import org.springframework.web.context.request.ServletRequestAttributes;
|
||||
import org.springframework.web.servlet.LocaleResolver;
|
||||
|
||||
import com.ckfinder.connector.ServletContextFactory;
|
||||
import com.google.common.collect.Lists;
|
||||
import com.nis.web.service.SpringContextHolder;
|
||||
|
||||
/**
|
||||
* 字符串工具类, 继承org.apache.commons.lang3.StringUtils类
|
||||
*
|
||||
* @author ThinkGem
|
||||
* @version 2013-05-22
|
||||
*/
|
||||
public class StringUtils extends org.apache.commons.lang3.StringUtils {
|
||||
|
||||
private static final char SEPARATOR = '_';
|
||||
private static final String CHARSET_NAME = "UTF-8";
|
||||
public static final String HASH_ALGORITHM = "SHA-1";
|
||||
public static final int HASH_INTERATIONS = 1024;
|
||||
public static final int SALT_SIZE = 8;
|
||||
|
||||
/**
|
||||
* 转换为字节数组
|
||||
*
|
||||
* @param str
|
||||
* @return
|
||||
*/
|
||||
public static byte[] getBytes(String str) {
|
||||
if (str != null) {
|
||||
try {
|
||||
return str.getBytes(CHARSET_NAME);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return null;
|
||||
}
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为字节数组
|
||||
*
|
||||
* @param str
|
||||
* @return
|
||||
*/
|
||||
public static String toString(byte[] bytes) {
|
||||
try {
|
||||
return new String(bytes, CHARSET_NAME);
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
return EMPTY;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 是否包含字符串
|
||||
*
|
||||
* @param str
|
||||
* 验证字符串
|
||||
* @param strs
|
||||
* 字符串组
|
||||
* @return 包含返回true
|
||||
*/
|
||||
public static boolean inString(String str, String... strs) {
|
||||
if (str != null) {
|
||||
for (String s : strs) {
|
||||
if (str.equals(trim(s))) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* 替换掉HTML标签方法
|
||||
*/
|
||||
public static String replaceHtml(String html) {
|
||||
if (isBlank(html)) {
|
||||
return "";
|
||||
}
|
||||
String regEx = "<.+?>";
|
||||
Pattern p = Pattern.compile(regEx);
|
||||
Matcher m = p.matcher(html);
|
||||
String s = m.replaceAll("");
|
||||
return s;
|
||||
}
|
||||
|
||||
/**
|
||||
* 替换为手机识别的HTML,去掉样式及属性,保留回车。
|
||||
*
|
||||
* @param html
|
||||
* @return
|
||||
*/
|
||||
public static String replaceMobileHtml(String html) {
|
||||
if (html == null) {
|
||||
return "";
|
||||
}
|
||||
return html.replaceAll("<([a-z]+?)\\s+?.*?>", "<$1>");
|
||||
}
|
||||
|
||||
/**
|
||||
* 替换为手机识别的HTML,去掉样式及属性,保留回车。
|
||||
*
|
||||
* @param txt
|
||||
* @return
|
||||
*/
|
||||
public static String toHtml(String txt) {
|
||||
if (txt == null) {
|
||||
return "";
|
||||
}
|
||||
return replace(replace(Encodes.escapeHtml(txt), "\n", "<br/>"), "\t", " ");
|
||||
}
|
||||
|
||||
/**
|
||||
* 缩略字符串(不区分中英文字符)
|
||||
*
|
||||
* @param str
|
||||
* 目标字符串
|
||||
* @param length
|
||||
* 截取长度
|
||||
* @return
|
||||
*/
|
||||
public static String abbr(String str, int length) {
|
||||
if (str == null) {
|
||||
return "";
|
||||
}
|
||||
try {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
int currentLength = 0;
|
||||
for (char c : replaceHtml(StringEscapeUtils.unescapeHtml4(str)).toCharArray()) {
|
||||
currentLength += String.valueOf(c).getBytes("GBK").length;
|
||||
if (currentLength <= length - 3) {
|
||||
sb.append(c);
|
||||
} else {
|
||||
sb.append("...");
|
||||
break;
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
public static String abbr2(String param, int length) {
|
||||
if (param == null) {
|
||||
return "";
|
||||
}
|
||||
StringBuffer result = new StringBuffer();
|
||||
int n = 0;
|
||||
char temp;
|
||||
boolean isCode = false; // 是不是HTML代码
|
||||
boolean isHTML = false; // 是不是HTML特殊字符,如
|
||||
for (int i = 0; i < param.length(); i++) {
|
||||
temp = param.charAt(i);
|
||||
if (temp == '<') {
|
||||
isCode = true;
|
||||
} else if (temp == '&') {
|
||||
isHTML = true;
|
||||
} else if (temp == '>' && isCode) {
|
||||
n = n - 1;
|
||||
isCode = false;
|
||||
} else if (temp == ';' && isHTML) {
|
||||
isHTML = false;
|
||||
}
|
||||
try {
|
||||
if (!isCode && !isHTML) {
|
||||
n += String.valueOf(temp).getBytes("GBK").length;
|
||||
}
|
||||
} catch (UnsupportedEncodingException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
|
||||
if (n <= length - 3) {
|
||||
result.append(temp);
|
||||
} else {
|
||||
result.append("...");
|
||||
break;
|
||||
}
|
||||
}
|
||||
// 取出截取字符串中的HTML标记
|
||||
String temp_result = result.toString().replaceAll("(>)[^<>]*(<?)", "$1$2");
|
||||
// 去掉不需要结素标记的HTML标记
|
||||
temp_result = temp_result.replaceAll(
|
||||
"</?(AREA|BASE|BASEFONT|BODY|BR|COL|COLGROUP|DD|DT|FRAME|HEAD|HR|HTML|IMG|INPUT|ISINDEX|LI|LINK|META|OPTION|P|PARAM|TBODY|TD|TFOOT|TH|THEAD|TR|area|base|basefont|body|br|col|colgroup|dd|dt|frame|head|hr|html|img|input|isindex|li|link|meta|option|p|param|tbody|td|tfoot|th|thead|tr)[^<>]*/?>",
|
||||
"");
|
||||
// 去掉成对的HTML标记
|
||||
temp_result = temp_result.replaceAll("<([a-zA-Z]+)[^<>]*>(.*?)</\\1>", "$2");
|
||||
// 用正则表达式取出标记
|
||||
Pattern p = Pattern.compile("<([a-zA-Z]+)[^<>]*>");
|
||||
Matcher m = p.matcher(temp_result);
|
||||
List<String> endHTML = Lists.newArrayList();
|
||||
while (m.find()) {
|
||||
endHTML.add(m.group(1));
|
||||
}
|
||||
// 补全不成对的HTML标记
|
||||
for (int i = endHTML.size() - 1; i >= 0; i--) {
|
||||
result.append("</");
|
||||
result.append(endHTML.get(i));
|
||||
result.append(">");
|
||||
}
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为Double类型
|
||||
*/
|
||||
public static Double toDouble(Object val) {
|
||||
if (val == null) {
|
||||
return 0D;
|
||||
}
|
||||
try {
|
||||
return Double.valueOf(trim(val.toString()));
|
||||
} catch (Exception e) {
|
||||
return 0D;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为Float类型
|
||||
*/
|
||||
public static Float toFloat(Object val) {
|
||||
return toDouble(val).floatValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为Long类型
|
||||
*/
|
||||
public static Long toLong(Object val) {
|
||||
return toDouble(val).longValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为Integer类型
|
||||
*/
|
||||
public static Integer toInteger(Object val) {
|
||||
return toLong(val).intValue();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得i18n字符串
|
||||
*/
|
||||
public static String getMessage(String code, Object[] args) {
|
||||
LocaleResolver localLocaleResolver = (LocaleResolver) SpringContextHolder.getBean(LocaleResolver.class);
|
||||
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
|
||||
.getRequest();
|
||||
Locale localLocale = localLocaleResolver.resolveLocale(request);
|
||||
return SpringContextHolder.getApplicationContext().getMessage(code, args, localLocale);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获得用户远程地址
|
||||
*/
|
||||
public static String getRemoteAddr(HttpServletRequest request) {
|
||||
String remoteAddr = request.getHeader("X-Real-IP");
|
||||
if (isNotBlank(remoteAddr)) {
|
||||
remoteAddr = request.getHeader("X-Forwarded-For");
|
||||
} else if (isNotBlank(remoteAddr)) {
|
||||
remoteAddr = request.getHeader("Proxy-Client-IP");
|
||||
} else if (isNotBlank(remoteAddr)) {
|
||||
remoteAddr = request.getHeader("WL-Proxy-Client-IP");
|
||||
}
|
||||
return remoteAddr != null ? remoteAddr : request.getRemoteAddr();
|
||||
}
|
||||
|
||||
/**
|
||||
* 驼峰命名法工具
|
||||
*
|
||||
* @return toCamelCase("hello_world") == "helloWorld"
|
||||
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
|
||||
* toUnderScoreCase("helloWorld") = "hello_world"
|
||||
*/
|
||||
public static String toCamelCase(String s) {
|
||||
if (s == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
s = s.toLowerCase();
|
||||
|
||||
StringBuilder sb = new StringBuilder(s.length());
|
||||
boolean upperCase = false;
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char c = s.charAt(i);
|
||||
|
||||
if (c == SEPARATOR) {
|
||||
upperCase = true;
|
||||
} else if (upperCase) {
|
||||
sb.append(Character.toUpperCase(c));
|
||||
upperCase = false;
|
||||
} else {
|
||||
sb.append(c);
|
||||
}
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 驼峰命名法工具
|
||||
*
|
||||
* @return toCamelCase("hello_world") == "helloWorld"
|
||||
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
|
||||
* toUnderScoreCase("helloWorld") = "hello_world"
|
||||
*/
|
||||
public static String toCapitalizeCamelCase(String s) {
|
||||
if (s == null) {
|
||||
return null;
|
||||
}
|
||||
s = toCamelCase(s);
|
||||
return s.substring(0, 1).toUpperCase() + s.substring(1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 驼峰命名法工具
|
||||
*
|
||||
* @return toCamelCase("hello_world") == "helloWorld"
|
||||
* toCapitalizeCamelCase("hello_world") == "HelloWorld"
|
||||
* toUnderScoreCase("helloWorld") = "hello_world"
|
||||
*/
|
||||
public static String toUnderScoreCase(String s) {
|
||||
if (s == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
StringBuilder sb = new StringBuilder();
|
||||
boolean upperCase = false;
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char c = s.charAt(i);
|
||||
|
||||
boolean nextUpperCase = true;
|
||||
|
||||
if (i < (s.length() - 1)) {
|
||||
nextUpperCase = Character.isUpperCase(s.charAt(i + 1));
|
||||
}
|
||||
|
||||
if ((i > 0) && Character.isUpperCase(c)) {
|
||||
if (!upperCase || !nextUpperCase) {
|
||||
sb.append(SEPARATOR);
|
||||
}
|
||||
upperCase = true;
|
||||
} else {
|
||||
upperCase = false;
|
||||
}
|
||||
|
||||
sb.append(Character.toLowerCase(c));
|
||||
}
|
||||
|
||||
return sb.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 如果不为空,则设置值
|
||||
*
|
||||
* @param target
|
||||
* @param source
|
||||
*/
|
||||
public static void setValueIfNotBlank(String target, String source) {
|
||||
if (isNotBlank(source)) {
|
||||
target = source;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换为JS获取对象值,生成三目运算返回结果
|
||||
*
|
||||
* @param objectString
|
||||
* 对象串 例如:row.user.id
|
||||
* 返回:!row?'':!row.user?'':!row.user.id?'':row.user.id
|
||||
*/
|
||||
public static String jsGetVal(String objectString) {
|
||||
StringBuilder result = new StringBuilder();
|
||||
StringBuilder val = new StringBuilder();
|
||||
String[] vals = split(objectString, ".");
|
||||
for (int i = 0; i < vals.length; i++) {
|
||||
val.append("." + vals[i]);
|
||||
result.append("!" + (val.substring(1)) + "?'':");
|
||||
}
|
||||
result.append(val.substring(1));
|
||||
return result.toString();
|
||||
}
|
||||
|
||||
/**
|
||||
* 生成安全的密码,生成随机的16位salt并经过1024次 sha-1 hash
|
||||
*/
|
||||
public static String entryptPassword(String plainPassword) {
|
||||
byte[] salt = Digests.generateSalt(SALT_SIZE);
|
||||
byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
|
||||
return Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword);
|
||||
}
|
||||
|
||||
/**
|
||||
* 验证密码
|
||||
*
|
||||
* @param plainPassword
|
||||
* 明文密码
|
||||
* @param password
|
||||
* 密文密码
|
||||
* @return 验证成功返回true
|
||||
*/
|
||||
public static boolean validatePassword(String plainPassword, String password) {
|
||||
byte[] salt = Encodes.decodeHex(password.substring(0, 16));
|
||||
byte[] hashPassword = Digests.sha1(plainPassword.getBytes(), salt, HASH_INTERATIONS);
|
||||
return password.equals(Encodes.encodeHex(salt) + Encodes.encodeHex(hashPassword));
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取上传文件的根目录
|
||||
*
|
||||
* @return
|
||||
*/
|
||||
public static String getUserfilesBaseDir() {
|
||||
String dir = Configurations.getStringProperty("userfiles.basedir", "");
|
||||
try {
|
||||
if (StringUtils.isBlank(dir)) {
|
||||
dir = ServletContextFactory.getServletContext().getRealPath("/");
|
||||
} else {
|
||||
dir = ServletContextFactory.getServletContext().getRealPath("/") + dir;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
return "";
|
||||
}
|
||||
|
||||
if (!dir.endsWith("/")) {
|
||||
dir += "/";
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* <p>
|
||||
* 判断字符串是否为空. 为空条件:全角\半角\tab 等没有实际意义的字符.
|
||||
* 具体参看{@link Character#isWhitespace(char)}对空格的定义.
|
||||
* </p>
|
||||
*
|
||||
* <pre>
|
||||
* StringUtils.isBlank(" ") = true 为半角空格
|
||||
* StringUtils.isBlank(" ") = true 为全角空格
|
||||
* StringUtils.isBlank(" ") = true 为tab键
|
||||
* </pre>
|
||||
*
|
||||
* @param str
|
||||
* 字符串
|
||||
* @return <code>true<code> 字符串为空 ,<code>false</code> 不为空
|
||||
*/
|
||||
public static boolean strIsBlank(String str) {
|
||||
int strLen;
|
||||
if (str == null || (strLen = str.length()) == 0) {
|
||||
return true;
|
||||
}
|
||||
for (int i = 0; i < strLen; i++) {
|
||||
if ((Character.isWhitespace(str.charAt(i)) == false)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
}
|
||||
83
src/main/java/com/nis/util/TreeUtil.java
Normal file
83
src/main/java/com/nis/util/TreeUtil.java
Normal file
@@ -0,0 +1,83 @@
|
||||
package com.nis.util;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
import com.nis.domain.SysMenu;
|
||||
import com.nis.web.security.UserUtils;
|
||||
|
||||
/**
|
||||
* 将树构建成上下层结构
|
||||
* @author Administrator
|
||||
*
|
||||
*/
|
||||
public final class TreeUtil {
|
||||
|
||||
private List<SysMenu> menuList = new ArrayList<SysMenu>();
|
||||
|
||||
public TreeUtil(List<SysMenu> menuList) {
|
||||
this.menuList = menuList;
|
||||
}
|
||||
|
||||
public List<SysMenu> buildTree(){
|
||||
List<SysMenu> newMenuList = new ArrayList<SysMenu>();
|
||||
|
||||
for (SysMenu menu : menuList) {
|
||||
if (menu.getParent().getId().equals(1l)) {
|
||||
if (isBusinessOfAdmin(menu.getName())) {
|
||||
continue;
|
||||
}
|
||||
build(menu);
|
||||
newMenuList.add(menu);
|
||||
}
|
||||
}
|
||||
|
||||
return newMenuList;
|
||||
}
|
||||
|
||||
/**
|
||||
* 过滤admin的业务功能
|
||||
* @return
|
||||
*/
|
||||
private boolean isBusinessOfAdmin(String menuName) {
|
||||
if (UserUtils.getUser().isAdmin()
|
||||
&& menuName.equals(Constants.SYS_BUSINESS_MENU_NAME) ) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
|
||||
private void build(SysMenu rootMenu) {
|
||||
|
||||
List<SysMenu> children = getChildren(rootMenu);
|
||||
|
||||
if ( !StringUtil.isEmpty(children) ) {
|
||||
rootMenu.setChildren(children);
|
||||
for (SysMenu child : children) {
|
||||
if (StringUtils.isBlank(child.getHref())) { //根据url是否为空判断结束
|
||||
build(child);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
private List<SysMenu> getChildren(SysMenu rootMenu){
|
||||
|
||||
List<SysMenu> children = new ArrayList<SysMenu>();
|
||||
|
||||
for(SysMenu child : menuList) {
|
||||
if (rootMenu.getId().equals(child.getParent().getId())) {
|
||||
children.add(child);
|
||||
}
|
||||
}
|
||||
|
||||
return children;
|
||||
|
||||
}
|
||||
|
||||
|
||||
|
||||
}
|
||||
@@ -0,0 +1,278 @@
|
||||
/**
|
||||
*@Title: ElasticsearchSqlUtil.java
|
||||
*@Package com.nis.util
|
||||
*@Description TODO
|
||||
*@author dell
|
||||
*@date 2016年10月17日 下午4:09:17
|
||||
*@version 版本号
|
||||
*/
|
||||
package com.nis.util.elasticsearch;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Modifier;
|
||||
import java.text.ParseException;
|
||||
import java.text.SimpleDateFormat;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Arrays;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.Iterator;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.ibatis.mapping.ResultMap;
|
||||
import org.apache.ibatis.mapping.ResultMapping;
|
||||
import org.apache.ibatis.session.SqlSessionFactory;
|
||||
import org.apache.log4j.Logger;
|
||||
import org.json.JSONArray;
|
||||
import org.json.JSONException;
|
||||
import org.json.JSONObject;
|
||||
|
||||
import com.nis.domain.LogEntity;
|
||||
import com.nis.domain.Page;
|
||||
import com.nis.util.Constants;
|
||||
import com.nis.util.JsonMapper;
|
||||
import com.nis.util.StringUtil;
|
||||
import com.nis.util.StringUtils;
|
||||
import com.nis.util.httpclient.HttpClientUtil;
|
||||
import com.nis.web.service.SpringContextHolder;
|
||||
|
||||
/**
|
||||
* @ClassName: ElasticsearchSqlUtil.java
|
||||
* @Description: 在service中替代oracle查询
|
||||
* @author (wx)
|
||||
* @date 2016年10月17日 下午4:09:17
|
||||
* @version V1.0
|
||||
*/
|
||||
@SuppressWarnings({"unchecked","rawtypes"})
|
||||
public class ElasticsearchSqlDao {
|
||||
private static final Logger logger=Logger.getLogger(ElasticsearchSqlDao.class);
|
||||
private static final SqlSessionFactory sqlSessionFactory=SpringContextHolder.getBean(SqlSessionFactory.class);
|
||||
private static final Map<Class,Map<String,String>> fieldsMapMap=new HashMap<>();
|
||||
public void init(Class clazz){
|
||||
Map<String,String> fieldsMap=new HashMap<>();
|
||||
ResultMap data=sqlSessionFactory.getConfiguration().getResultMap(clazz.getSimpleName()+"Map");
|
||||
List<ResultMapping> mappingList=data.getResultMappings();
|
||||
for(ResultMapping map:mappingList){
|
||||
fieldsMap.put(map.getColumn().toUpperCase(), map.getProperty());
|
||||
}
|
||||
fieldsMapMap.put(clazz, fieldsMap);
|
||||
}
|
||||
/**
|
||||
* 获取elasticsearch中的mapping field
|
||||
* getSearchFields(这里用一句话描述这个方法的作用)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param page
|
||||
* @param clazz
|
||||
* @return
|
||||
*List<String>
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
private String getSearchFields(Page<?> page,Class<?> clazz){
|
||||
String fields=page.getFields();
|
||||
|
||||
if(StringUtil.isBlank(fields)){
|
||||
fields="*";
|
||||
}else{
|
||||
String[] fieldArray=fields.split(",");
|
||||
for(String field :fieldArray){
|
||||
if(fieldsMapMap.get(clazz).containsKey(field.toUpperCase())){
|
||||
fields=fields.replace(field, fieldsMapMap.get(clazz).get(field.toUpperCase()));
|
||||
}
|
||||
}
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
/**
|
||||
*
|
||||
* getWhereCondition(where 条件转换)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param entity
|
||||
* @param givenDateFormat
|
||||
* @return
|
||||
* @throws ParseException
|
||||
* @throws IllegalArgumentException
|
||||
* @throws IllegalAccessException
|
||||
*String
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
private String getWhereCondition(LogEntity<?> entity,SimpleDateFormat givenDateFormat) throws ParseException, IllegalArgumentException, IllegalAccessException{
|
||||
StringBuffer where=new StringBuffer();
|
||||
//使用反射获取entity的所有字段值
|
||||
Class clazz=entity.getClass();
|
||||
List<Field> fieldList=new ArrayList<Field>();
|
||||
fieldList.addAll(Arrays.asList(clazz.getDeclaredFields()));
|
||||
fieldList.addAll(Arrays.asList(clazz.getSuperclass().getDeclaredFields()));
|
||||
|
||||
for(Field field:fieldList){
|
||||
if(Modifier.isFinal(field.getModifiers()))continue;
|
||||
if(Modifier.isPrivate(field.getModifiers())||Modifier.isProtected(field.getModifiers())){
|
||||
field.setAccessible(true);
|
||||
}
|
||||
String type=field.getType().getSimpleName();
|
||||
Object value=field.get(entity);
|
||||
if(value==null)continue;
|
||||
if(field.getName().endsWith("StartTime")){
|
||||
String startTime=value.toString();
|
||||
if(!StringUtil.isBlank(startTime)){
|
||||
String fieldName=field.getName()
|
||||
.replace("search", "")
|
||||
.replace("Start", "");
|
||||
fieldName=fieldName.replace(fieldName.substring(0, 1),fieldName.substring(0, 1).toLowerCase());
|
||||
where.append(" AND "+fieldName +">=");
|
||||
where.append(givenDateFormat.parse(startTime).getTime()/1000);
|
||||
|
||||
}
|
||||
}else if(field.getName().endsWith("EndTime")){
|
||||
String endTime=value.toString();
|
||||
if(!StringUtil.isBlank(endTime)){
|
||||
String fieldName=field.getName()
|
||||
.replace("search", "")
|
||||
.replace("End", "");
|
||||
fieldName=fieldName.replace(fieldName.substring(0, 1),fieldName.substring(0, 1).toLowerCase());
|
||||
where.append(" AND "+fieldName +"<");
|
||||
where.append(givenDateFormat.parse(endTime).getTime()/1000);
|
||||
|
||||
}
|
||||
}else{
|
||||
String fieldName=field.getName().replace("search", "");
|
||||
fieldName=fieldName.replace(fieldName.substring(0, 1),fieldName.substring(0, 1).toLowerCase());
|
||||
if(fieldsMapMap.get(clazz).containsValue(fieldName)){
|
||||
if("Date".equals(type)){
|
||||
Date date=(Date)value;
|
||||
where.append(" AND "+fieldName+"=");
|
||||
where.append(date.getTime()/1000);
|
||||
}else{
|
||||
where.append(" AND "+fieldName +"=");
|
||||
where.append("'"+value.toString()+"'");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
where.delete(0, " AND ".length());
|
||||
return where.toString().trim();
|
||||
}
|
||||
/**
|
||||
*
|
||||
* getOderbys(排序转换)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param page
|
||||
* @param clazz
|
||||
* @return
|
||||
*String
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
private String getOderbys(Page page,Class clazz){
|
||||
String orderBy=page.getOrderBy();
|
||||
for(String field :orderBy.split(" ")){
|
||||
if(fieldsMapMap.get(clazz).containsKey(field.toUpperCase())){
|
||||
orderBy=orderBy.replace(field, fieldsMapMap.get(clazz).get(field.toUpperCase()));
|
||||
}
|
||||
}
|
||||
return orderBy;
|
||||
|
||||
}
|
||||
|
||||
public String geneEs4SQL(Class clazz,Page<?> page,LogEntity<?> entity) throws ParseException, IllegalArgumentException, IllegalAccessException{
|
||||
if(!fieldsMapMap.containsKey(clazz)){
|
||||
this.init(clazz);
|
||||
}
|
||||
SimpleDateFormat givenDateFormat=new SimpleDateFormat(Constants.SEARCH_DATEFORMAT);
|
||||
String indexName=clazz.getSimpleName().toUpperCase();
|
||||
String fields=getSearchFields(page, clazz);
|
||||
String where=getWhereCondition(entity, givenDateFormat);
|
||||
where=StringUtils.isBlank(where)?" ":" where "+where;
|
||||
String groupBy="";
|
||||
String orderBy=getOderbys(page,clazz);
|
||||
orderBy=StringUtils.isBlank(orderBy)?" ":" ORDER BY "+orderBy;
|
||||
String pageInfo=getPageInfo(page);
|
||||
String sql="SELECT "+fields+
|
||||
" FROM "+indexName+where+groupBy+orderBy+pageInfo;
|
||||
logger.info("es-sql:"+sql);
|
||||
return sql.replaceAll(" ", "%20").replaceAll("<", "%3C").replaceAll(">", "%3E");
|
||||
}
|
||||
public String search(LogEntity<?> entity,String acticeSys) throws ParseException, IllegalArgumentException, IllegalAccessException, ClientProtocolException, IOException{
|
||||
String sql=geneEs4SQL(entity.getClass(),entity.getPage(),entity);
|
||||
if(acticeSys.equals(Constants.ACTIVESYS_C)){
|
||||
logger.info("查询C版ES");
|
||||
return HttpClientUtil.get("http://"+Constants.SEARCH_ES_HOSTANDPORT_C+"/_sql?sql="+sql);
|
||||
}else if(acticeSys.equals(Constants.ACTIVESYS_A)){
|
||||
logger.info("查询A版ES");
|
||||
return HttpClientUtil.get("http://"+Constants.SEARCH_ES_HOSTANDPORT_A+"/_sql?sql="+sql);
|
||||
}else{
|
||||
logger.info("查询B版ES");
|
||||
return HttpClientUtil.get("http://"+Constants.SEARCH_ES_HOSTANDPORT_B+"/_sql?sql="+sql);
|
||||
}
|
||||
}
|
||||
private String getPageInfo(Page page){
|
||||
int pageNo=page.getPageNo();
|
||||
int pageSize=page.getPageSize();
|
||||
return " limit "+(pageNo-1)*pageSize+", "+page.getPageSize();
|
||||
}
|
||||
/**
|
||||
*
|
||||
* findLogs(查询方法)
|
||||
* (初始化好list 之后传入方法,查询结果会加入到list中)
|
||||
* @param logList
|
||||
* @param esHostAndPort
|
||||
* @param log
|
||||
* @param givenFormat
|
||||
* @throws ParseException
|
||||
* @throws JSONException
|
||||
* @throws IllegalArgumentException
|
||||
* @throws IllegalAccessException
|
||||
*void
|
||||
* @throws IOException
|
||||
* @throws ClientProtocolException
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public void findLogs(List logList,LogEntity<?> log,String activeSys) throws ParseException, JSONException, IllegalArgumentException, IllegalAccessException, ClientProtocolException, IOException{
|
||||
Class clazz=log.getClass();
|
||||
JSONObject obj=new JSONObject(search(log,activeSys));
|
||||
long count=obj.getJSONObject("hits").getLong("total");
|
||||
long took=obj.getLong("took");
|
||||
logger.info("search by es cost: "+took+"ms");
|
||||
log.getPage().setCount(count);
|
||||
if(count>0){
|
||||
JSONArray resultJson=obj.getJSONObject("hits").getJSONArray("hits");
|
||||
for(int i=0;i<resultJson.length();i++){
|
||||
JSONObject re=(JSONObject)resultJson.get(i);
|
||||
JSONObject json=re.getJSONObject("_source");
|
||||
Iterator it=json.keys();
|
||||
//找出时间字段,由于中心时间戳没有存毫秒,在这里转换时间的时候需要将10位的时间戳转换为13位的时间戳
|
||||
//默认以Time结尾的字段为时间字段
|
||||
while(it.hasNext()){
|
||||
String key=it.next().toString();
|
||||
if(key.endsWith("Time")&&json.has(key)&&!json.isNull(key)){
|
||||
long time=json.getLong(key);
|
||||
if(String.valueOf(time).length()==10){
|
||||
json.put(key, time*1000);
|
||||
}
|
||||
}
|
||||
}
|
||||
logList.add(JsonMapper.fromJsonString(json.toString(), clazz));
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
/**
|
||||
* main(这里用一句话描述这个方法的作用)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param args
|
||||
*void
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public static void main(String[] args) {
|
||||
// TODO Auto-generated method stub
|
||||
StringBuffer sf=new StringBuffer(" AND 1=1");
|
||||
System.out.println(sf.delete(0, " AND".length()).toString());
|
||||
}
|
||||
|
||||
}
|
||||
59
src/main/java/com/nis/util/excel/ExcelField.java
Normal file
59
src/main/java/com/nis/util/excel/ExcelField.java
Normal file
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.util.excel;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* Excel注解定义
|
||||
* @author ThinkGem
|
||||
* @version 2013-03-10
|
||||
*/
|
||||
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.TYPE})
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface ExcelField {
|
||||
|
||||
/**
|
||||
* 导出字段名(默认调用当前字段的“get”方法,如指定导出字段为对象,请填写“对象名.对象属性”,例:“area.name”、“office.name”)
|
||||
*/
|
||||
String value() default "";
|
||||
|
||||
/**
|
||||
* 导出字段标题(需要添加批注请用“**”分隔,标题**批注,仅对导出模板有效)
|
||||
*/
|
||||
String title();
|
||||
|
||||
/**
|
||||
* 字段类型(0:导出导入;1:仅导出;2:仅导入)
|
||||
*/
|
||||
int type() default 0;
|
||||
|
||||
/**
|
||||
* 导出字段对齐方式(0:自动;1:靠左;2:居中;3:靠右)
|
||||
*/
|
||||
int align() default 0;
|
||||
|
||||
/**
|
||||
* 导出字段字段排序(升序)
|
||||
*/
|
||||
int sort() default 0;
|
||||
|
||||
/**
|
||||
* 如果是字典类型,请设置字典的type值
|
||||
*/
|
||||
String dictType() default "";
|
||||
|
||||
/**
|
||||
* 反射类型
|
||||
*/
|
||||
Class<?> fieldType() default Class.class;
|
||||
|
||||
/**
|
||||
* 字段归属组(根据分组导出导入)
|
||||
*/
|
||||
int[] groups() default {};
|
||||
}
|
||||
476
src/main/java/com/nis/util/excel/ExportExcel.java
Normal file
476
src/main/java/com/nis/util/excel/ExportExcel.java
Normal file
@@ -0,0 +1,476 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.util.excel;
|
||||
|
||||
import java.io.FileNotFoundException;
|
||||
import java.io.FileOutputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.Date;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import javax.servlet.http.HttpServletResponse;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.CellStyle;
|
||||
import org.apache.poi.ss.usermodel.Comment;
|
||||
import org.apache.poi.ss.usermodel.DataFormat;
|
||||
import org.apache.poi.ss.usermodel.Font;
|
||||
import org.apache.poi.ss.usermodel.IndexedColors;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.apache.poi.ss.util.CellRangeAddress;
|
||||
import org.apache.poi.xssf.streaming.SXSSFWorkbook;
|
||||
import org.apache.poi.xssf.usermodel.XSSFClientAnchor;
|
||||
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.nis.util.DictUtils;
|
||||
import com.nis.util.Encodes;
|
||||
import com.nis.util.Reflections;
|
||||
|
||||
/**
|
||||
* 导出Excel文件(导出“XLSX”格式,支持大数据量导出 @see org.apache.poi.ss.SpreadsheetVersion)
|
||||
* @author ThinkGem
|
||||
* @version 2013-04-21
|
||||
*/
|
||||
public class ExportExcel {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(ExportExcel.class);
|
||||
|
||||
/**
|
||||
* 工作薄对象
|
||||
*/
|
||||
private SXSSFWorkbook wb;
|
||||
|
||||
/**
|
||||
* 工作表对象
|
||||
*/
|
||||
private Sheet sheet;
|
||||
|
||||
/**
|
||||
* 样式列表
|
||||
*/
|
||||
private Map<String, CellStyle> styles;
|
||||
|
||||
/**
|
||||
* 当前行号
|
||||
*/
|
||||
private int rownum;
|
||||
|
||||
/**
|
||||
* 注解列表(Object[]{ ExcelField, Field/Method })
|
||||
*/
|
||||
List<Object[]> annotationList = Lists.newArrayList();
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
* @param title 表格标题,传“空值”,表示无标题
|
||||
* @param cls 实体对象,通过annotation.ExportField获取标题
|
||||
*/
|
||||
public ExportExcel(String title, Class<?> cls){
|
||||
this(title, cls, 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
* @param title 表格标题,传“空值”,表示无标题
|
||||
* @param cls 实体对象,通过annotation.ExportField获取标题
|
||||
* @param type 导出类型(1:导出数据;2:导出模板)
|
||||
* @param groups 导入分组
|
||||
*/
|
||||
public ExportExcel(String title, Class<?> cls, int type, int... groups){
|
||||
// Get annotation field
|
||||
Field[] fs = cls.getDeclaredFields();
|
||||
for (Field f : fs){
|
||||
ExcelField ef = f.getAnnotation(ExcelField.class);
|
||||
if (ef != null && (ef.type()==0 || ef.type()==type)){
|
||||
if (groups!=null && groups.length>0){
|
||||
boolean inGroup = false;
|
||||
for (int g : groups){
|
||||
if (inGroup){
|
||||
break;
|
||||
}
|
||||
for (int efg : ef.groups()){
|
||||
if (g == efg){
|
||||
inGroup = true;
|
||||
annotationList.add(new Object[]{ef, f});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}else{
|
||||
annotationList.add(new Object[]{ef, f});
|
||||
}
|
||||
}
|
||||
}
|
||||
// Get annotation method
|
||||
Method[] ms = cls.getDeclaredMethods();
|
||||
for (Method m : ms){
|
||||
ExcelField ef = m.getAnnotation(ExcelField.class);
|
||||
if (ef != null && (ef.type()==0 || ef.type()==type)){
|
||||
if (groups!=null && groups.length>0){
|
||||
boolean inGroup = false;
|
||||
for (int g : groups){
|
||||
if (inGroup){
|
||||
break;
|
||||
}
|
||||
for (int efg : ef.groups()){
|
||||
if (g == efg){
|
||||
inGroup = true;
|
||||
annotationList.add(new Object[]{ef, m});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}else{
|
||||
annotationList.add(new Object[]{ef, m});
|
||||
}
|
||||
}
|
||||
}
|
||||
// Field sorting
|
||||
Collections.sort(annotationList, new Comparator<Object[]>() {
|
||||
public int compare(Object[] o1, Object[] o2) {
|
||||
return new Integer(((ExcelField)o1[0]).sort()).compareTo(
|
||||
new Integer(((ExcelField)o2[0]).sort()));
|
||||
};
|
||||
});
|
||||
// Initialize
|
||||
List<String> headerList = Lists.newArrayList();
|
||||
for (Object[] os : annotationList){
|
||||
String t = ((ExcelField)os[0]).title();
|
||||
// 如果是导出,则去掉注释
|
||||
if (type==1){
|
||||
String[] ss = StringUtils.split(t, "**", 2);
|
||||
if (ss.length==2){
|
||||
t = ss[0];
|
||||
}
|
||||
}
|
||||
headerList.add(t);
|
||||
}
|
||||
initialize(title, headerList);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
* @param title 表格标题,传“空值”,表示无标题
|
||||
* @param headers 表头数组
|
||||
*/
|
||||
public ExportExcel(String title, String[] headers) {
|
||||
initialize(title, Lists.newArrayList(headers));
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
* @param title 表格标题,传“空值”,表示无标题
|
||||
* @param headerList 表头列表
|
||||
*/
|
||||
public ExportExcel(String title, List<String> headerList) {
|
||||
initialize(title, headerList);
|
||||
}
|
||||
|
||||
/**
|
||||
* 初始化函数
|
||||
* @param title 表格标题,传“空值”,表示无标题
|
||||
* @param headerList 表头列表
|
||||
*/
|
||||
private void initialize(String title, List<String> headerList) {
|
||||
this.wb = new SXSSFWorkbook(500);
|
||||
this.sheet = wb.createSheet("Export");
|
||||
this.styles = createStyles(wb);
|
||||
// Create title
|
||||
if (StringUtils.isNotBlank(title)){
|
||||
Row titleRow = sheet.createRow(rownum++);
|
||||
titleRow.setHeightInPoints(30);
|
||||
Cell titleCell = titleRow.createCell(0);
|
||||
titleCell.setCellStyle(styles.get("title"));
|
||||
titleCell.setCellValue(title);
|
||||
sheet.addMergedRegion(new CellRangeAddress(titleRow.getRowNum(),
|
||||
titleRow.getRowNum(), titleRow.getRowNum(), headerList.size()-1));
|
||||
}
|
||||
// Create header
|
||||
if (headerList == null){
|
||||
throw new RuntimeException("headerList not null!");
|
||||
}
|
||||
Row headerRow = sheet.createRow(rownum++);
|
||||
headerRow.setHeightInPoints(16);
|
||||
for (int i = 0; i < headerList.size(); i++) {
|
||||
Cell cell = headerRow.createCell(i);
|
||||
cell.setCellStyle(styles.get("header"));
|
||||
String[] ss = StringUtils.split(headerList.get(i), "**", 2);
|
||||
if (ss.length==2){
|
||||
cell.setCellValue(ss[0]);
|
||||
Comment comment = this.sheet.createDrawingPatriarch().createCellComment(
|
||||
new XSSFClientAnchor(0, 0, 0, 0, (short) 3, 3, (short) 5, 6));
|
||||
comment.setString(new XSSFRichTextString(ss[1]));
|
||||
cell.setCellComment(comment);
|
||||
}else{
|
||||
cell.setCellValue(headerList.get(i));
|
||||
}
|
||||
sheet.autoSizeColumn(i);
|
||||
}
|
||||
for (int i = 0; i < headerList.size(); i++) {
|
||||
int colWidth = sheet.getColumnWidth(i)*2;
|
||||
sheet.setColumnWidth(i, colWidth < 3000 ? 3000 : colWidth);
|
||||
}
|
||||
log.debug("Initialize success.");
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建表格样式
|
||||
* @param wb 工作薄对象
|
||||
* @return 样式列表
|
||||
*/
|
||||
private Map<String, CellStyle> createStyles(Workbook wb) {
|
||||
Map<String, CellStyle> styles = new HashMap<String, CellStyle>();
|
||||
|
||||
CellStyle style = wb.createCellStyle();
|
||||
style.setAlignment(CellStyle.ALIGN_CENTER);
|
||||
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
|
||||
Font titleFont = wb.createFont();
|
||||
titleFont.setFontName("Arial");
|
||||
titleFont.setFontHeightInPoints((short) 16);
|
||||
titleFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
|
||||
style.setFont(titleFont);
|
||||
styles.put("title", style);
|
||||
|
||||
style = wb.createCellStyle();
|
||||
style.setVerticalAlignment(CellStyle.VERTICAL_CENTER);
|
||||
style.setBorderRight(CellStyle.BORDER_THIN);
|
||||
style.setRightBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
|
||||
style.setBorderLeft(CellStyle.BORDER_THIN);
|
||||
style.setLeftBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
|
||||
style.setBorderTop(CellStyle.BORDER_THIN);
|
||||
style.setTopBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
|
||||
style.setBorderBottom(CellStyle.BORDER_THIN);
|
||||
style.setBottomBorderColor(IndexedColors.GREY_50_PERCENT.getIndex());
|
||||
Font dataFont = wb.createFont();
|
||||
dataFont.setFontName("Arial");
|
||||
dataFont.setFontHeightInPoints((short) 10);
|
||||
style.setFont(dataFont);
|
||||
styles.put("data", style);
|
||||
|
||||
style = wb.createCellStyle();
|
||||
style.cloneStyleFrom(styles.get("data"));
|
||||
style.setAlignment(CellStyle.ALIGN_LEFT);
|
||||
styles.put("data1", style);
|
||||
|
||||
style = wb.createCellStyle();
|
||||
style.cloneStyleFrom(styles.get("data"));
|
||||
style.setAlignment(CellStyle.ALIGN_CENTER);
|
||||
styles.put("data2", style);
|
||||
|
||||
style = wb.createCellStyle();
|
||||
style.cloneStyleFrom(styles.get("data"));
|
||||
style.setAlignment(CellStyle.ALIGN_RIGHT);
|
||||
styles.put("data3", style);
|
||||
|
||||
style = wb.createCellStyle();
|
||||
style.cloneStyleFrom(styles.get("data"));
|
||||
// style.setWrapText(true);
|
||||
style.setAlignment(CellStyle.ALIGN_CENTER);
|
||||
style.setFillForegroundColor(IndexedColors.GREY_50_PERCENT.getIndex());
|
||||
style.setFillPattern(CellStyle.SOLID_FOREGROUND);
|
||||
Font headerFont = wb.createFont();
|
||||
headerFont.setFontName("Arial");
|
||||
headerFont.setFontHeightInPoints((short) 10);
|
||||
headerFont.setBoldweight(Font.BOLDWEIGHT_BOLD);
|
||||
headerFont.setColor(IndexedColors.WHITE.getIndex());
|
||||
style.setFont(headerFont);
|
||||
styles.put("header", style);
|
||||
|
||||
return styles;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加一行
|
||||
* @return 行对象
|
||||
*/
|
||||
public Row addRow(){
|
||||
return sheet.createRow(rownum++);
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* 添加一个单元格
|
||||
* @param row 添加的行
|
||||
* @param column 添加列号
|
||||
* @param val 添加值
|
||||
* @return 单元格对象
|
||||
*/
|
||||
public Cell addCell(Row row, int column, Object val){
|
||||
return this.addCell(row, column, val, 0, Class.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加一个单元格
|
||||
* @param row 添加的行
|
||||
* @param column 添加列号
|
||||
* @param val 添加值
|
||||
* @param align 对齐方式(1:靠左;2:居中;3:靠右)
|
||||
* @return 单元格对象
|
||||
*/
|
||||
public Cell addCell(Row row, int column, Object val, int align, Class<?> fieldType){
|
||||
Cell cell = row.createCell(column);
|
||||
CellStyle style = styles.get("data"+(align>=1&&align<=3?align:""));
|
||||
try {
|
||||
if (val == null){
|
||||
cell.setCellValue("");
|
||||
} else if (val instanceof String) {
|
||||
cell.setCellValue((String) val);
|
||||
} else if (val instanceof Integer) {
|
||||
cell.setCellValue((Integer) val);
|
||||
} else if (val instanceof Long) {
|
||||
cell.setCellValue((Long) val);
|
||||
} else if (val instanceof Double) {
|
||||
cell.setCellValue((Double) val);
|
||||
} else if (val instanceof Float) {
|
||||
cell.setCellValue((Float) val);
|
||||
} else if (val instanceof Date) {
|
||||
DataFormat format = wb.createDataFormat();
|
||||
style.setDataFormat(format.getFormat("yyyy-MM-dd"));
|
||||
cell.setCellValue((Date) val);
|
||||
} else {
|
||||
if (fieldType != Class.class){
|
||||
cell.setCellValue((String)fieldType.getMethod("setValue", Object.class).invoke(null, val));
|
||||
}else{
|
||||
cell.setCellValue((String)Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
|
||||
"fieldtype."+val.getClass().getSimpleName()+"Type")).getMethod("setValue", Object.class).invoke(null, val));
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.info("Set cell value ["+row.getRowNum()+","+column+"] error: " + ex.toString());
|
||||
cell.setCellValue(val.toString());
|
||||
}
|
||||
cell.setCellStyle(style);
|
||||
return cell;
|
||||
}
|
||||
|
||||
/**
|
||||
* 添加数据(通过annotation.ExportField添加数据)
|
||||
* @return list 数据列表
|
||||
*/
|
||||
public <E> ExportExcel setDataList(List<E> list){
|
||||
for (E e : list){
|
||||
int colunm = 0;
|
||||
Row row = this.addRow();
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Object[] os : annotationList){
|
||||
ExcelField ef = (ExcelField)os[0];
|
||||
Object val = null;
|
||||
// Get entity value
|
||||
try{
|
||||
if (StringUtils.isNotBlank(ef.value())){
|
||||
val = Reflections.invokeGetter(e, ef.value());
|
||||
}else{
|
||||
if (os[1] instanceof Field){
|
||||
val = Reflections.invokeGetter(e, ((Field)os[1]).getName());
|
||||
}else if (os[1] instanceof Method){
|
||||
val = Reflections.invokeMethod(e, ((Method)os[1]).getName(), new Class[] {}, new Object[] {});
|
||||
}
|
||||
}
|
||||
// If is dict, get dict label
|
||||
if (StringUtils.isNotBlank(ef.dictType())){
|
||||
val = DictUtils.getDictLabel(val==null?"":val.toString(), ef.dictType(), "");
|
||||
}
|
||||
}catch(Exception ex) {
|
||||
// Failure to ignore
|
||||
log.info(ex.toString());
|
||||
val = "";
|
||||
}
|
||||
this.addCell(row, colunm++, val, ef.align(), ef.fieldType());
|
||||
sb.append(val + ", ");
|
||||
}
|
||||
log.debug("Write success: ["+row.getRowNum()+"] "+sb.toString());
|
||||
}
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出数据流
|
||||
* @param os 输出数据流
|
||||
*/
|
||||
public ExportExcel write(OutputStream os) throws IOException{
|
||||
wb.write(os);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出到客户端
|
||||
* @param fileName 输出文件名
|
||||
*/
|
||||
public ExportExcel write(HttpServletResponse response, String fileName) throws IOException{
|
||||
response.reset();
|
||||
response.setContentType("application/octet-stream; charset=utf-8");
|
||||
response.setHeader("Content-Disposition", "attachment; filename="+Encodes.urlEncode(fileName));
|
||||
write(response.getOutputStream());
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 输出到文件
|
||||
* @param fileName 输出文件名
|
||||
*/
|
||||
public ExportExcel writeFile(String name) throws FileNotFoundException, IOException{
|
||||
FileOutputStream os = new FileOutputStream(name);
|
||||
this.write(os);
|
||||
return this;
|
||||
}
|
||||
|
||||
/**
|
||||
* 清理临时文件
|
||||
*/
|
||||
public ExportExcel dispose(){
|
||||
wb.dispose();
|
||||
return this;
|
||||
}
|
||||
|
||||
// /**
|
||||
// * 导出测试
|
||||
// */
|
||||
// public static void main(String[] args) throws Throwable {
|
||||
//
|
||||
// List<String> headerList = Lists.newArrayList();
|
||||
// for (int i = 1; i <= 10; i++) {
|
||||
// headerList.add("表头"+i);
|
||||
// }
|
||||
//
|
||||
// List<String> dataRowList = Lists.newArrayList();
|
||||
// for (int i = 1; i <= headerList.size(); i++) {
|
||||
// dataRowList.add("数据"+i);
|
||||
// }
|
||||
//
|
||||
// List<List<String>> dataList = Lists.newArrayList();
|
||||
// for (int i = 1; i <=1000000; i++) {
|
||||
// dataList.add(dataRowList);
|
||||
// }
|
||||
//
|
||||
// ExportExcel ee = new ExportExcel("表格标题", headerList);
|
||||
//
|
||||
// for (int i = 0; i < dataList.size(); i++) {
|
||||
// Row row = ee.addRow();
|
||||
// for (int j = 0; j < dataList.get(i).size(); j++) {
|
||||
// ee.addCell(row, j, dataList.get(i).get(j));
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// ee.writeFile("target/export.xlsx");
|
||||
//
|
||||
// ee.dispose();
|
||||
//
|
||||
// log.debug("Export success.");
|
||||
//
|
||||
// }
|
||||
|
||||
}
|
||||
369
src/main/java/com/nis/util/excel/ImportExcel.java
Normal file
369
src/main/java/com/nis/util/excel/ImportExcel.java
Normal file
@@ -0,0 +1,369 @@
|
||||
/**
|
||||
* Copyright © 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
|
||||
*/
|
||||
package com.nis.util.excel;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.lang.reflect.Field;
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.commons.lang3.StringUtils;
|
||||
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
|
||||
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
|
||||
import org.apache.poi.ss.usermodel.Cell;
|
||||
import org.apache.poi.ss.usermodel.DateUtil;
|
||||
import org.apache.poi.ss.usermodel.Row;
|
||||
import org.apache.poi.ss.usermodel.Sheet;
|
||||
import org.apache.poi.ss.usermodel.Workbook;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.web.multipart.MultipartFile;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.nis.util.DictUtils;
|
||||
import com.nis.util.Reflections;
|
||||
|
||||
/**
|
||||
* 导入Excel文件(支持“XLS”和“XLSX”格式)
|
||||
* @author ThinkGem
|
||||
* @version 2013-03-10
|
||||
*/
|
||||
public class ImportExcel {
|
||||
|
||||
private static Logger log = LoggerFactory.getLogger(ImportExcel.class);
|
||||
|
||||
/**
|
||||
* 工作薄对象
|
||||
*/
|
||||
private Workbook wb;
|
||||
|
||||
/**
|
||||
* 工作表对象
|
||||
*/
|
||||
private Sheet sheet;
|
||||
|
||||
/**
|
||||
* 标题行号
|
||||
*/
|
||||
private int headerNum;
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
* @param path 导入文件,读取第一个工作表
|
||||
* @param headerNum 标题行号,数据行号=标题行号+1
|
||||
* @throws InvalidFormatException
|
||||
* @throws IOException
|
||||
*/
|
||||
public ImportExcel(String fileName, int headerNum)
|
||||
throws InvalidFormatException, IOException {
|
||||
this(new File(fileName), headerNum);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
* @param path 导入文件对象,读取第一个工作表
|
||||
* @param headerNum 标题行号,数据行号=标题行号+1
|
||||
* @throws InvalidFormatException
|
||||
* @throws IOException
|
||||
*/
|
||||
public ImportExcel(File file, int headerNum)
|
||||
throws InvalidFormatException, IOException {
|
||||
this(file, headerNum, 0);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
* @param path 导入文件
|
||||
* @param headerNum 标题行号,数据行号=标题行号+1
|
||||
* @param sheetIndex 工作表编号
|
||||
* @throws InvalidFormatException
|
||||
* @throws IOException
|
||||
*/
|
||||
public ImportExcel(String fileName, int headerNum, int sheetIndex)
|
||||
throws InvalidFormatException, IOException {
|
||||
this(new File(fileName), headerNum, sheetIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
* @param path 导入文件对象
|
||||
* @param headerNum 标题行号,数据行号=标题行号+1
|
||||
* @param sheetIndex 工作表编号
|
||||
* @throws InvalidFormatException
|
||||
* @throws IOException
|
||||
*/
|
||||
public ImportExcel(File file, int headerNum, int sheetIndex)
|
||||
throws InvalidFormatException, IOException {
|
||||
this(file.getName(), new FileInputStream(file), headerNum, sheetIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
* @param file 导入文件对象
|
||||
* @param headerNum 标题行号,数据行号=标题行号+1
|
||||
* @param sheetIndex 工作表编号
|
||||
* @throws InvalidFormatException
|
||||
* @throws IOException
|
||||
*/
|
||||
public ImportExcel(MultipartFile multipartFile, int headerNum, int sheetIndex)
|
||||
throws InvalidFormatException, IOException {
|
||||
this(multipartFile.getOriginalFilename(), multipartFile.getInputStream(), headerNum, sheetIndex);
|
||||
}
|
||||
|
||||
/**
|
||||
* 构造函数
|
||||
* @param path 导入文件对象
|
||||
* @param headerNum 标题行号,数据行号=标题行号+1
|
||||
* @param sheetIndex 工作表编号
|
||||
* @throws InvalidFormatException
|
||||
* @throws IOException
|
||||
*/
|
||||
public ImportExcel(String fileName, InputStream is, int headerNum, int sheetIndex)
|
||||
throws InvalidFormatException, IOException {
|
||||
if (StringUtils.isBlank(fileName)){
|
||||
throw new RuntimeException("导入文档为空!");
|
||||
}else if(fileName.toLowerCase().endsWith("xls")){
|
||||
this.wb = new HSSFWorkbook(is);
|
||||
}else if(fileName.toLowerCase().endsWith("xlsx")){
|
||||
this.wb = new XSSFWorkbook(is);
|
||||
}else{
|
||||
throw new RuntimeException("文档格式不正确!");
|
||||
}
|
||||
if (this.wb.getNumberOfSheets()<sheetIndex){
|
||||
throw new RuntimeException("文档中没有工作表!");
|
||||
}
|
||||
this.sheet = this.wb.getSheetAt(sheetIndex);
|
||||
this.headerNum = headerNum;
|
||||
log.debug("Initialize success.");
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取行对象
|
||||
* @param rownum
|
||||
* @return
|
||||
*/
|
||||
public Row getRow(int rownum){
|
||||
return this.sheet.getRow(rownum);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取数据行号
|
||||
* @return
|
||||
*/
|
||||
public int getDataRowNum(){
|
||||
return headerNum+1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取最后一个数据行号
|
||||
* @return
|
||||
*/
|
||||
public int getLastDataRowNum(){
|
||||
return this.sheet.getLastRowNum()+headerNum;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取最后一个列号
|
||||
* @return
|
||||
*/
|
||||
public int getLastCellNum(){
|
||||
return this.getRow(headerNum).getLastCellNum();
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取单元格值
|
||||
* @param row 获取的行
|
||||
* @param column 获取单元格列号
|
||||
* @return 单元格值
|
||||
*/
|
||||
public Object getCellValue(Row row, int column){
|
||||
Object val = "";
|
||||
try{
|
||||
Cell cell = row.getCell(column);
|
||||
if (cell != null){
|
||||
if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC){
|
||||
val = cell.getNumericCellValue();
|
||||
}else if (cell.getCellType() == Cell.CELL_TYPE_STRING){
|
||||
val = cell.getStringCellValue();
|
||||
}else if (cell.getCellType() == Cell.CELL_TYPE_FORMULA){
|
||||
val = cell.getCellFormula();
|
||||
}else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN){
|
||||
val = cell.getBooleanCellValue();
|
||||
}else if (cell.getCellType() == Cell.CELL_TYPE_ERROR){
|
||||
val = cell.getErrorCellValue();
|
||||
}
|
||||
}
|
||||
}catch (Exception e) {
|
||||
return val;
|
||||
}
|
||||
return val;
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取导入数据列表
|
||||
* @param cls 导入对象类型
|
||||
* @param groups 导入分组
|
||||
*/
|
||||
public <E> List<E> getDataList(Class<E> cls, int... groups) throws InstantiationException, IllegalAccessException{
|
||||
List<Object[]> annotationList = Lists.newArrayList();
|
||||
// Get annotation field
|
||||
Field[] fs = cls.getDeclaredFields();
|
||||
for (Field f : fs){
|
||||
ExcelField ef = f.getAnnotation(ExcelField.class);
|
||||
if (ef != null && (ef.type()==0 || ef.type()==2)){
|
||||
if (groups!=null && groups.length>0){
|
||||
boolean inGroup = false;
|
||||
for (int g : groups){
|
||||
if (inGroup){
|
||||
break;
|
||||
}
|
||||
for (int efg : ef.groups()){
|
||||
if (g == efg){
|
||||
inGroup = true;
|
||||
annotationList.add(new Object[]{ef, f});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}else{
|
||||
annotationList.add(new Object[]{ef, f});
|
||||
}
|
||||
}
|
||||
}
|
||||
// Get annotation method
|
||||
Method[] ms = cls.getDeclaredMethods();
|
||||
for (Method m : ms){
|
||||
ExcelField ef = m.getAnnotation(ExcelField.class);
|
||||
if (ef != null && (ef.type()==0 || ef.type()==2)){
|
||||
if (groups!=null && groups.length>0){
|
||||
boolean inGroup = false;
|
||||
for (int g : groups){
|
||||
if (inGroup){
|
||||
break;
|
||||
}
|
||||
for (int efg : ef.groups()){
|
||||
if (g == efg){
|
||||
inGroup = true;
|
||||
annotationList.add(new Object[]{ef, m});
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}else{
|
||||
annotationList.add(new Object[]{ef, m});
|
||||
}
|
||||
}
|
||||
}
|
||||
// Field sorting
|
||||
Collections.sort(annotationList, new Comparator<Object[]>() {
|
||||
public int compare(Object[] o1, Object[] o2) {
|
||||
return new Integer(((ExcelField)o1[0]).sort()).compareTo(
|
||||
new Integer(((ExcelField)o2[0]).sort()));
|
||||
};
|
||||
});
|
||||
//log.debug("Import column count:"+annotationList.size());
|
||||
// Get excel data
|
||||
List<E> dataList = Lists.newArrayList();
|
||||
for (int i = this.getDataRowNum(); i < this.getLastDataRowNum(); i++) {
|
||||
E e = (E)cls.newInstance();
|
||||
int column = 0;
|
||||
Row row = this.getRow(i);
|
||||
StringBuilder sb = new StringBuilder();
|
||||
for (Object[] os : annotationList){
|
||||
Object val = this.getCellValue(row, column++);
|
||||
if (val != null){
|
||||
ExcelField ef = (ExcelField)os[0];
|
||||
// If is dict type, get dict value
|
||||
if (StringUtils.isNotBlank(ef.dictType())){
|
||||
val = DictUtils.getDictCode(ef.dictType(), val.toString(), "");
|
||||
//log.debug("Dictionary type value: ["+i+","+colunm+"] " + val);
|
||||
}
|
||||
// Get param type and type cast
|
||||
Class<?> valType = Class.class;
|
||||
if (os[1] instanceof Field){
|
||||
valType = ((Field)os[1]).getType();
|
||||
}else if (os[1] instanceof Method){
|
||||
Method method = ((Method)os[1]);
|
||||
if ("get".equals(method.getName().substring(0, 3))){
|
||||
valType = method.getReturnType();
|
||||
}else if("set".equals(method.getName().substring(0, 3))){
|
||||
valType = ((Method)os[1]).getParameterTypes()[0];
|
||||
}
|
||||
}
|
||||
//log.debug("Import value type: ["+i+","+column+"] " + valType);
|
||||
try {
|
||||
if (valType == String.class){
|
||||
String s = String.valueOf(val.toString());
|
||||
if(StringUtils.endsWith(s, ".0")){
|
||||
val = StringUtils.substringBefore(s, ".0");
|
||||
}else{
|
||||
val = String.valueOf(val.toString());
|
||||
}
|
||||
}else if (valType == Integer.class){
|
||||
val = Double.valueOf(val.toString()).intValue();
|
||||
}else if (valType == Long.class){
|
||||
val = Double.valueOf(val.toString()).longValue();
|
||||
}else if (valType == Double.class){
|
||||
val = Double.valueOf(val.toString());
|
||||
}else if (valType == Float.class){
|
||||
val = Float.valueOf(val.toString());
|
||||
}else if (valType == Date.class){
|
||||
val = DateUtil.getJavaDate((Double)val);
|
||||
}else{
|
||||
if (ef.fieldType() != Class.class){
|
||||
val = ef.fieldType().getMethod("getValue", String.class).invoke(null, val.toString());
|
||||
}else{
|
||||
val = Class.forName(this.getClass().getName().replaceAll(this.getClass().getSimpleName(),
|
||||
"fieldtype."+valType.getSimpleName()+"Type")).getMethod("getValue", String.class).invoke(null, val.toString());
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.info("Get cell value ["+i+","+column+"] error: " + ex.toString());
|
||||
val = null;
|
||||
}
|
||||
// set entity value
|
||||
if (os[1] instanceof Field){
|
||||
Reflections.invokeSetter(e, ((Field)os[1]).getName(), val);
|
||||
}else if (os[1] instanceof Method){
|
||||
String mthodName = ((Method)os[1]).getName();
|
||||
if ("get".equals(mthodName.substring(0, 3))){
|
||||
mthodName = "set"+StringUtils.substringAfter(mthodName, "get");
|
||||
}
|
||||
Reflections.invokeMethod(e, mthodName, new Class[] {valType}, new Object[] {val});
|
||||
}
|
||||
}
|
||||
sb.append(val+", ");
|
||||
}
|
||||
dataList.add(e);
|
||||
log.debug("Read success: ["+i+"] "+sb.toString());
|
||||
}
|
||||
return dataList;
|
||||
}
|
||||
|
||||
// /**
|
||||
// * 导入测试
|
||||
// */
|
||||
// public static void main(String[] args) throws Throwable {
|
||||
//
|
||||
// ImportExcel ei = new ImportExcel("target/export.xlsx", 1);
|
||||
//
|
||||
// for (int i = ei.getDataRowNum(); i < ei.getLastDataRowNum(); i++) {
|
||||
// Row row = ei.getRow(i);
|
||||
// for (int j = 0; j < ei.getLastCellNum(); j++) {
|
||||
// Object val = ei.getCellValue(row, j);
|
||||
// System.out.print(val+", ");
|
||||
// }
|
||||
// System.out.print("\n");
|
||||
// }
|
||||
//
|
||||
// }
|
||||
|
||||
}
|
||||
44
src/main/java/com/nis/util/excel/fieldtype/RoleListType.java
Normal file
44
src/main/java/com/nis/util/excel/fieldtype/RoleListType.java
Normal file
@@ -0,0 +1,44 @@
|
||||
package com.nis.util.excel.fieldtype;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.google.common.collect.Lists;
|
||||
import com.nis.domain.SysRole;
|
||||
import com.nis.util.Collections3;
|
||||
import com.nis.util.StringUtils;
|
||||
import com.nis.web.service.RoleService;
|
||||
import com.nis.web.service.SpringContextHolder;
|
||||
|
||||
public class RoleListType {
|
||||
|
||||
private static RoleService roleService = SpringContextHolder.getBean(RoleService.class);
|
||||
|
||||
/**
|
||||
* 获取对象值(导入)
|
||||
*/
|
||||
public static Object getValue(String val) {
|
||||
List<SysRole> roleList = Lists.newArrayList();
|
||||
List<SysRole> allRoleList = roleService.findAllRole();
|
||||
for (String s : StringUtils.split(val, ",")){
|
||||
for (SysRole e : allRoleList){
|
||||
if (StringUtils.trimToEmpty(s).equals(e.getName())){
|
||||
roleList.add(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
return roleList.size()>0?roleList:null;
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置对象值(导出)
|
||||
*/
|
||||
public static String setValue(Object val) {
|
||||
if (val != null){
|
||||
@SuppressWarnings("unchecked")
|
||||
List<SysRole> roleList = (List<SysRole>)val;
|
||||
return Collections3.extractToString(roleList, "name", ", ");
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
}
|
||||
116
src/main/java/com/nis/util/httpclient/HttpClientUtil.java
Normal file
116
src/main/java/com/nis/util/httpclient/HttpClientUtil.java
Normal file
@@ -0,0 +1,116 @@
|
||||
/**
|
||||
*@Title: HttpClientBean.java
|
||||
*@Package com.nis.util.httpclient
|
||||
*@Description TODO
|
||||
*@author dell
|
||||
*@date 2016年11月7日 下午2:36:26
|
||||
*@version 版本号
|
||||
*/
|
||||
package com.nis.util.httpclient;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
import org.apache.http.NameValuePair;
|
||||
import org.apache.http.client.ClientProtocolException;
|
||||
import org.apache.http.client.entity.UrlEncodedFormEntity;
|
||||
import org.apache.http.client.methods.CloseableHttpResponse;
|
||||
import org.apache.http.client.methods.HttpGet;
|
||||
import org.apache.http.client.methods.HttpPost;
|
||||
import org.apache.http.impl.client.CloseableHttpClient;
|
||||
import org.apache.http.impl.client.HttpClients;
|
||||
import org.apache.http.message.BasicNameValuePair;
|
||||
import org.apache.http.util.EntityUtils;
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
/**
|
||||
* @ClassName: HttpClientBean.java
|
||||
* @Description: TODO
|
||||
* @author (dell)
|
||||
* @date 2016年11月7日 下午2:36:26
|
||||
* @version V1.0
|
||||
*/
|
||||
public class HttpClientUtil {
|
||||
protected final Logger logger = Logger.getLogger(HttpClientUtil.class);
|
||||
/**
|
||||
* 处理get请求.
|
||||
* @param url 请求路径
|
||||
* @return json
|
||||
* @throws IOException
|
||||
* @throws ClientProtocolException
|
||||
*/
|
||||
public static String get(String url) throws ClientProtocolException, IOException{
|
||||
//实例化httpclient
|
||||
CloseableHttpClient httpclient = HttpClients.createDefault();
|
||||
//实例化get方法
|
||||
HttpGet httpget = new HttpGet(url);
|
||||
//请求结果
|
||||
CloseableHttpResponse response = null;
|
||||
String content ="";
|
||||
// try {
|
||||
//执行get方法
|
||||
response = httpclient.execute(httpget);
|
||||
// if(response.getStatusLine().getStatusCode()==200){
|
||||
content = EntityUtils.toString(response.getEntity(),"utf-8");
|
||||
// }
|
||||
// } catch (ClientProtocolException e) {
|
||||
// e.printStackTrace();
|
||||
// } catch (IOException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
return content;
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理post请求.
|
||||
* @param url 请求路径
|
||||
* @param params 参数
|
||||
* @return json
|
||||
* @throws IOException
|
||||
* @throws ClientProtocolException
|
||||
*/
|
||||
public String post(String url,Map<String, String> params) throws ClientProtocolException, IOException{
|
||||
//实例化httpClient
|
||||
CloseableHttpClient httpclient = HttpClients.createDefault();
|
||||
//实例化post方法
|
||||
HttpPost httpPost = new HttpPost(url);
|
||||
//处理参数
|
||||
List<NameValuePair> nvps = new ArrayList <NameValuePair>();
|
||||
Set<String> keySet = params.keySet();
|
||||
for(String key : keySet) {
|
||||
nvps.add(new BasicNameValuePair(key, params.get(key)));
|
||||
}
|
||||
//结果
|
||||
CloseableHttpResponse response = null;
|
||||
String content="";
|
||||
// try {
|
||||
//提交的参数
|
||||
UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(nvps, "UTF-8");
|
||||
//将参数给post方法
|
||||
httpPost.setEntity(uefEntity);
|
||||
//执行post方法
|
||||
response = httpclient.execute(httpPost);
|
||||
// if(response.getStatusLine().getStatusCode()==200){
|
||||
content = EntityUtils.toString(response.getEntity(),"utf-8");
|
||||
// System.out.println(content);
|
||||
// }
|
||||
// } catch (ClientProtocolException e) {
|
||||
// e.printStackTrace();
|
||||
// } catch (IOException e) {
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
return content;
|
||||
}
|
||||
public static void main(String[] args) throws ClientProtocolException, IOException {
|
||||
HttpClientUtil hd = new HttpClientUtil();
|
||||
hd.get("http://10.0.6.115:9200/_sql?sql=select * from dfipportlog-2016-09-07-15 limit 1 10");
|
||||
Map<String,String> map = new HashMap();
|
||||
map.put("id","1");
|
||||
hd.post("http://localhost:8080/springMVC/menu/getChildren.do",map);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
/**
|
||||
*@Title: IdleConnectionEvictor.java
|
||||
*@Package com.nis.util.httpclient
|
||||
*@Description TODO
|
||||
*@author dell
|
||||
*@date 2016年11月7日 下午2:20:35
|
||||
*@version 版本号
|
||||
*/
|
||||
package com.nis.util.httpclient;
|
||||
|
||||
import org.apache.http.conn.HttpClientConnectionManager;
|
||||
|
||||
/**
|
||||
* @ClassName: IdleConnectionEvictor.java
|
||||
* @Description: TODO
|
||||
* @author (dell)
|
||||
* @date 2016年11月7日 下午2:20:35
|
||||
* @version V1.0
|
||||
*/
|
||||
public class IdleConnectionEvictor extends Thread{
|
||||
private final HttpClientConnectionManager connMgr;
|
||||
|
||||
private Integer waitTime;
|
||||
|
||||
private volatile boolean shutdown;
|
||||
|
||||
public IdleConnectionEvictor(HttpClientConnectionManager connMgr,Integer waitTime) {
|
||||
this.connMgr = connMgr;
|
||||
this.waitTime = waitTime;
|
||||
this.start();
|
||||
}
|
||||
|
||||
public void run() {
|
||||
try {
|
||||
while (!shutdown) {
|
||||
synchronized (this) {
|
||||
wait(waitTime);
|
||||
// 关闭失效的连接
|
||||
connMgr.closeExpiredConnections();
|
||||
}
|
||||
}
|
||||
} catch (InterruptedException ex) {
|
||||
// 结束
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 销毁释放资源
|
||||
*/
|
||||
public void shutdown() {
|
||||
shutdown = true;
|
||||
synchronized (this) {
|
||||
notifyAll();
|
||||
}
|
||||
}
|
||||
}
|
||||
235
src/main/java/com/nis/util/redis/JedisClusterPipeline.java
Normal file
235
src/main/java/com/nis/util/redis/JedisClusterPipeline.java
Normal file
@@ -0,0 +1,235 @@
|
||||
/**
|
||||
* Copyright: Copyright (c) 2015
|
||||
*
|
||||
* @author youaremoon
|
||||
* @date 2016年6月25日
|
||||
* @version V1.0
|
||||
*/
|
||||
package com.nis.util.redis;
|
||||
|
||||
import java.io.Closeable;
|
||||
import java.lang.reflect.Field;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Queue;
|
||||
|
||||
import redis.clients.jedis.BinaryJedisCluster;
|
||||
import redis.clients.jedis.Client;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.JedisCluster;
|
||||
import redis.clients.jedis.JedisClusterConnectionHandler;
|
||||
import redis.clients.jedis.JedisClusterInfoCache;
|
||||
import redis.clients.jedis.JedisPool;
|
||||
import redis.clients.jedis.JedisSlotBasedConnectionHandler;
|
||||
import redis.clients.jedis.PipelineBase;
|
||||
import redis.clients.jedis.exceptions.JedisMovedDataException;
|
||||
import redis.clients.jedis.exceptions.JedisRedirectionException;
|
||||
import redis.clients.util.JedisClusterCRC16;
|
||||
import redis.clients.util.SafeEncoder;
|
||||
|
||||
/**
|
||||
* 在集群模式下提供批量操作的功能。 <br/>
|
||||
* 由于集群模式存在节点的动态添加删除,且client不能实时感知(只有在执行命令时才可能知道集群发生变更),
|
||||
* 因此,该实现不保证一定成功,建议在批量操作之前调用 refreshCluster() 方法重新获取集群信息。<br />
|
||||
* 应用需要保证不论成功还是失败都会调用close() 方法,否则可能会造成泄露。<br/>
|
||||
* 如果失败需要应用自己去重试,因此每个批次执行的命令数量需要控制。防止失败后重试的数量过多。<br />
|
||||
* 基于以上说明,建议在集群环境较稳定(增减节点不会过于频繁)的情况下使用,且允许失败或有对应的重试策略。<br />
|
||||
*
|
||||
* 该类非线程安全
|
||||
*
|
||||
* @author youaremoon
|
||||
* @version
|
||||
* @since Ver 1.1
|
||||
*/
|
||||
public class JedisClusterPipeline extends PipelineBase implements Closeable {
|
||||
// private static final Logger LOGGER = LoggerFactory.getLogger(JedisClusterPipeline.class);
|
||||
|
||||
// 部分字段没有对应的获取方法,只能采用反射来做
|
||||
// 你也可以去继承JedisCluster和JedisSlotBasedConnectionHandler来提供访问接口
|
||||
private static final Field FIELD_CONNECTION_HANDLER;
|
||||
private static final Field FIELD_CACHE;
|
||||
static {
|
||||
FIELD_CONNECTION_HANDLER = getField(BinaryJedisCluster.class, "connectionHandler");
|
||||
FIELD_CACHE = getField(JedisClusterConnectionHandler.class, "cache");
|
||||
}
|
||||
|
||||
private JedisSlotBasedConnectionHandler connectionHandler;
|
||||
private JedisClusterInfoCache clusterInfoCache;
|
||||
private Queue<Client> clients = new LinkedList<Client>(); // 根据顺序存储每个命令对应的Client
|
||||
private Map<JedisPool, Jedis> jedisMap = new HashMap<>(); // 用于缓存连接
|
||||
private boolean hasDataInBuf = false; // 是否有数据在缓存区
|
||||
|
||||
/**
|
||||
* 根据jedisCluster实例生成对应的JedisClusterPipeline
|
||||
* @param
|
||||
* @return
|
||||
*/
|
||||
public static JedisClusterPipeline pipelined(JedisCluster jedisCluster) {
|
||||
JedisClusterPipeline pipeline = new JedisClusterPipeline();
|
||||
pipeline.setJedisCluster(jedisCluster);
|
||||
return pipeline;
|
||||
}
|
||||
|
||||
public JedisClusterPipeline() {
|
||||
}
|
||||
|
||||
public void setJedisCluster(JedisCluster jedis) {
|
||||
connectionHandler = getValue(jedis, FIELD_CONNECTION_HANDLER);
|
||||
clusterInfoCache = getValue(connectionHandler, FIELD_CACHE);
|
||||
}
|
||||
|
||||
/**
|
||||
* 刷新集群信息,当集群信息发生变更时调用
|
||||
* @param
|
||||
* @return
|
||||
*/
|
||||
public void refreshCluster() {
|
||||
connectionHandler.renewSlotCache();
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步读取所有数据. 与syncAndReturnAll()相比,sync()只是没有对数据做反序列化
|
||||
*/
|
||||
public void sync() {
|
||||
innerSync(null);
|
||||
}
|
||||
|
||||
/**
|
||||
* 同步读取所有数据 并按命令顺序返回一个列表
|
||||
*
|
||||
* @return 按照命令的顺序返回所有的数据
|
||||
*/
|
||||
public List<Object> syncAndReturnAll() {
|
||||
List<Object> responseList = new ArrayList<Object>();
|
||||
|
||||
innerSync(responseList);
|
||||
|
||||
return responseList;
|
||||
}
|
||||
|
||||
private void innerSync(List<Object> formatted) {
|
||||
HashSet<Client> clientSet = new HashSet<Client>();
|
||||
|
||||
try {
|
||||
for (Client client : clients) {
|
||||
// 在sync()调用时其实是不需要解析结果数据的,但是如果不调用get方法,发生了JedisMovedDataException这样的错误应用是不知道的,因此需要调用get()来触发错误。
|
||||
// 其实如果Response的data属性可以直接获取,可以省掉解析数据的时间,然而它并没有提供对应方法,要获取data属性就得用反射,不想再反射了,所以就这样了
|
||||
Object data = generateResponse(client.getOne()).get();
|
||||
if (null != formatted) {
|
||||
formatted.add(data);
|
||||
}
|
||||
|
||||
// size相同说明所有的client都已经添加,就不用再调用add方法了
|
||||
if (clientSet.size() != jedisMap.size()) {
|
||||
clientSet.add(client);
|
||||
}
|
||||
}
|
||||
} catch (JedisRedirectionException jre) {
|
||||
if (jre instanceof JedisMovedDataException) {
|
||||
// if MOVED redirection occurred, rebuilds cluster's slot cache,
|
||||
// recommended by Redis cluster specification
|
||||
refreshCluster();
|
||||
}
|
||||
|
||||
throw jre;
|
||||
} finally {
|
||||
if (clientSet.size() != jedisMap.size()) {
|
||||
// 所有还没有执行过的client要保证执行(flush),防止放回连接池后后面的命令被污染
|
||||
for (Jedis jedis : jedisMap.values()) {
|
||||
if (clientSet.contains(jedis.getClient())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
flushCachedData(jedis);
|
||||
}
|
||||
}
|
||||
|
||||
hasDataInBuf = false;
|
||||
close();
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void close() {
|
||||
clean();
|
||||
|
||||
clients.clear();
|
||||
|
||||
for (Jedis jedis : jedisMap.values()) {
|
||||
if (hasDataInBuf) {
|
||||
flushCachedData(jedis);
|
||||
}
|
||||
|
||||
jedis.close();
|
||||
}
|
||||
|
||||
jedisMap.clear();
|
||||
|
||||
hasDataInBuf = false;
|
||||
}
|
||||
|
||||
private void flushCachedData(Jedis jedis) {
|
||||
try {
|
||||
jedis.getClient().getAll();
|
||||
} catch (RuntimeException ex) {
|
||||
// 其中一个client出问题,后面出问题的几率较大
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Client getClient(String key) {
|
||||
byte[] bKey = SafeEncoder.encode(key);
|
||||
|
||||
return getClient(bKey);
|
||||
}
|
||||
|
||||
@Override
|
||||
protected Client getClient(byte[] key) {
|
||||
Jedis jedis = getJedis(JedisClusterCRC16.getSlot(key));
|
||||
|
||||
Client client = jedis.getClient();
|
||||
clients.add(client);
|
||||
|
||||
return client;
|
||||
}
|
||||
|
||||
private Jedis getJedis(int slot) {
|
||||
JedisPool pool = clusterInfoCache.getSlotPool(slot);
|
||||
|
||||
// 根据pool从缓存中获取Jedis
|
||||
Jedis jedis = jedisMap.get(pool);
|
||||
if (null == jedis) {
|
||||
jedis = pool.getResource();
|
||||
jedisMap.put(pool, jedis);
|
||||
}
|
||||
|
||||
hasDataInBuf = true;
|
||||
return jedis;
|
||||
}
|
||||
|
||||
private static Field getField(Class<?> cls, String fieldName) {
|
||||
try {
|
||||
Field field = cls.getDeclaredField(fieldName);
|
||||
field.setAccessible(true);
|
||||
|
||||
return field;
|
||||
} catch (NoSuchFieldException | SecurityException e) {
|
||||
throw new RuntimeException("cannot find or access field '" + fieldName + "' from " + cls.getName(), e);
|
||||
}
|
||||
}
|
||||
|
||||
@SuppressWarnings({"unchecked" })
|
||||
private static <T> T getValue(Object obj, Field field) {
|
||||
try {
|
||||
return (T)field.get(obj);
|
||||
} catch (IllegalArgumentException | IllegalAccessException e) {
|
||||
// LOGGER.error("get value fail", e);
|
||||
|
||||
throw new RuntimeException(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
458
src/main/java/com/nis/util/redis/RedisDao.java
Normal file
458
src/main/java/com/nis/util/redis/RedisDao.java
Normal file
@@ -0,0 +1,458 @@
|
||||
/**
|
||||
*@Title: RedisUtil.java
|
||||
*@Package com.nis.demo
|
||||
*@Description TODO
|
||||
*@author dell
|
||||
*@date 2016年9月13日 下午3:05:45
|
||||
*@version 版本号
|
||||
*/
|
||||
package com.nis.util.redis;
|
||||
import java.io.IOException;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Map.Entry;
|
||||
import java.util.Set;
|
||||
|
||||
import javax.annotation.PostConstruct;
|
||||
import javax.annotation.PreDestroy;
|
||||
|
||||
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.nis.util.BeanHelper;
|
||||
import com.nis.util.Configurations;
|
||||
import com.nis.util.Constants;
|
||||
|
||||
import redis.clients.jedis.HostAndPort;
|
||||
import redis.clients.jedis.Jedis;
|
||||
import redis.clients.jedis.JedisCluster;
|
||||
import redis.clients.jedis.JedisPool;
|
||||
|
||||
/**
|
||||
* @ClassName: RedisUtil.java
|
||||
* @Description: TODO
|
||||
* @author (wx)
|
||||
* @date 2016年9月13日 下午3:05:45
|
||||
* @version V1.0
|
||||
*/
|
||||
public class RedisDao {
|
||||
protected final Logger logger = Logger.getLogger(RedisDao.class);
|
||||
private JedisCluster cluster=null;
|
||||
private JedisClusterPipeline jcp=null;
|
||||
|
||||
public void initCluster(int type) throws Exception{
|
||||
if(cluster==null && Constants.IS_OPEN_REDIS){
|
||||
//初始化连接池配置
|
||||
GenericObjectPoolConfig config= getPoolConfig();
|
||||
//初始化节点信息
|
||||
Set<HostAndPort> jedisHostAndNodeSet= initNodes();
|
||||
int connectionTimeout=Configurations.getIntProperty("redis.cluster.connectiontimeout", 100);
|
||||
int soTimeout=Configurations.getIntProperty("redis.cluster.sotimeout", 100);
|
||||
int maxAttempts=Configurations.getIntProperty("redis.cluster.maxattempts", 3);
|
||||
//构造单例集群实例,其内部由多个节点构成,每个节点都有自己的连接池
|
||||
cluster=new JedisCluster(jedisHostAndNodeSet,connectionTimeout,soTimeout,maxAttempts,config);
|
||||
}
|
||||
logger.info("--------------------init redis cluster-----------");
|
||||
}
|
||||
/**
|
||||
* getJedisCluster(初始化redis的cluster)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @return
|
||||
* @throws Exception
|
||||
*JedisCluster
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
@PostConstruct
|
||||
public JedisCluster getJedisCluster() throws Exception{
|
||||
initCluster(0);
|
||||
return cluster;
|
||||
}
|
||||
/**
|
||||
*
|
||||
* closeJedisCluster(关闭redis cluster的方法,在系统终止时使用)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @throws IOException
|
||||
*void
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
@PreDestroy
|
||||
public void closeJedisCluster() throws IOException{
|
||||
if(cluster!=null)
|
||||
cluster.close();
|
||||
}
|
||||
/**
|
||||
*
|
||||
* getPoolConfig(初始化连接池的配置,这里可以设置很多参数的,不过目前没加)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @return
|
||||
*GenericObjectPoolConfig
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
private GenericObjectPoolConfig getPoolConfig(){
|
||||
GenericObjectPoolConfig config=new GenericObjectPoolConfig();
|
||||
config.setMaxTotal(Configurations.getIntProperty("redis.pool.maxtotal", 500));//整个池的最大值
|
||||
config.setMaxIdle(Configurations.getIntProperty("redis.pool.maxidle", 100));//最大空闲
|
||||
config.setMaxWaitMillis(Configurations.getIntProperty("redis.pool.maxwaitmillis", -1));//获取不到永远等待
|
||||
config.setBlockWhenExhausted(Configurations.getBooleanProperty("redis.pool.blockwhenexhausted", true));
|
||||
config.setNumTestsPerEvictionRun(Configurations.getIntProperty("redis.pool.numtestsperevictionrun", Integer.MAX_VALUE));//always test all idle object
|
||||
config.setTestOnBorrow(Configurations.getBooleanProperty("redis.pool.testonborrow", true));
|
||||
config.setTestOnReturn(Configurations.getBooleanProperty("redis.pool.testonreturn", false));
|
||||
config.setTestWhileIdle(Configurations.getBooleanProperty("redis.pool.testwhileidle", true));//发呆过长时间是否先test一下
|
||||
config.setTimeBetweenEvictionRunsMillis(Configurations.getLongProperty("redis.pool.timebetweenevictionrunsmillis", 60000L));//-1不启动,默认1min一次
|
||||
config.setMinEvictableIdleTimeMillis(Configurations.getLongProperty("redis.pool.minevictableidletimemillis", 60000L));//可发呆的时间,10mins
|
||||
return config;
|
||||
}
|
||||
/**
|
||||
*
|
||||
* initNodes(初始化节点信息)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @return
|
||||
* @throws Exception
|
||||
*Set<HostAndPort>
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
private Set<HostAndPort> initNodes() throws Exception{
|
||||
String hostAndPorts=Configurations.getStringProperty("redis.cluster.host_port", null);
|
||||
if(hostAndPorts==null)
|
||||
throw new RuntimeException("配置文件中redis.cluster.host_port为空!");
|
||||
String[] hostAndPort=hostAndPorts.split(",");
|
||||
Set<HostAndPort> jedisClusterNodes=new HashSet<HostAndPort>();
|
||||
for(String host_port:hostAndPort){
|
||||
String [] _host_port=host_port.split(":");
|
||||
if(_host_port.length!=2)
|
||||
throw new RuntimeException("配置文件中redis.cluster.host_port格式不正确!");
|
||||
HostAndPort node=new HostAndPort(_host_port[0],Integer.parseInt(_host_port[1]));
|
||||
jedisClusterNodes.add(node);
|
||||
}
|
||||
return jedisClusterNodes;
|
||||
}
|
||||
/**
|
||||
*
|
||||
* getClusterNodes(获取redis集群中的所有节点,每个节点都是一个连接池)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @return
|
||||
*Map<String,JedisPool>
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public Map<String, JedisPool> getClusterNodes(){
|
||||
return cluster==null?null:cluster.getClusterNodes();
|
||||
}
|
||||
/**
|
||||
*
|
||||
* getJedisClusterPipeline(获取redis cluster的 pipline.由于jedis没有实现,这里是用来一个第三方的pipline)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @return
|
||||
* @throws Exception
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public void getJedisClusterPipeline() throws Exception{
|
||||
if(cluster==null) cluster=getJedisCluster();;
|
||||
jcp=JedisClusterPipeline.pipelined(cluster);
|
||||
jcp.refreshCluster();//刷新集群状态
|
||||
}
|
||||
/**
|
||||
*
|
||||
* getJedisClusterPipeline(获取redis cluster的 pipline.由于jedis没有实现,这里是用来一个第三方的pipline)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @return
|
||||
*JedisClusterPipeline
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
// public JedisClusterPipeline getJedisClusterPipeline(JedisCluster cluster){
|
||||
// JedisClusterPipeline jcp=JedisClusterPipeline.pipelined(cluster);
|
||||
// jcp.refreshCluster();
|
||||
// return jcp;
|
||||
// }
|
||||
|
||||
|
||||
/**
|
||||
*
|
||||
* closeJedisClusterPipeline(关闭pipeline)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param jcp
|
||||
*void
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public void closeJedisClusterPipeline(){
|
||||
if(jcp!=null)
|
||||
jcp.close();
|
||||
}
|
||||
|
||||
/**
|
||||
*
|
||||
* closeJedisClusterPipeline(关闭pipeline)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param jcp
|
||||
*void
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
// public void closeJedisClusterPipeline(JedisClusterPipeline jcp){
|
||||
// if(jcp!=null)
|
||||
// jcp.close();
|
||||
// }
|
||||
/**
|
||||
*
|
||||
* * saveMaps(将对象转换成的Map保存到redis中)
|
||||
* (注意Date转换成long类型的时间戳然后以字符串的形式保存,蛋疼的jedis有问题,除了字符串跟byte[]数组就没别的保存类型了)
|
||||
* @param jcp//pipeLine
|
||||
* @param dataList//数据集合
|
||||
* @param tableName//实体类对应的表或者类名,用于生成唯一的hash key
|
||||
* @param keyField //实体类字段中表示唯一字段的字段名,其值用于生成唯一的hash key
|
||||
* @param clazz //类名
|
||||
* @throws Exception
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public void saveMaps(List<? extends Object> dataList ,String tableName,Class clazz,String keyField) throws Exception{
|
||||
logger.info("save maps start");
|
||||
if(cluster==null)cluster=getJedisCluster();
|
||||
if(jcp==null)getJedisClusterPipeline();
|
||||
long start=System.currentTimeMillis();
|
||||
// try{
|
||||
for(Object data:dataList){
|
||||
Map<String,String> dataMap=BeanHelper.transportBean2Map(clazz, data);
|
||||
jcp.hmset((tableName+"_"+dataMap.get(keyField)), dataMap);
|
||||
}
|
||||
jcp.sync();
|
||||
// }catch (Exception e) {
|
||||
// // TODO: handle exception
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
long end=System.currentTimeMillis();
|
||||
jcp.close();
|
||||
jcp=null;
|
||||
logger.info("save maps end, cost:"+(end-start));
|
||||
}
|
||||
/**
|
||||
*
|
||||
* updateMaps(更新redis中的对象)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param jcp
|
||||
* @param dataList
|
||||
* @param tableName
|
||||
* @param clazz
|
||||
* @param keyField
|
||||
* @throws Exception
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public void updateMaps(List<? extends Object> dataList ,String tableName,Class clazz,String keyField) throws Exception{
|
||||
logger.info("update maps start");
|
||||
if(cluster==null)cluster=getJedisCluster();
|
||||
if(jcp==null)getJedisClusterPipeline();
|
||||
long start=System.currentTimeMillis();
|
||||
// try{
|
||||
for(Object data:dataList){
|
||||
Map<String,String> dataMap=BeanHelper.transportBean2Map(clazz, data);
|
||||
jcp.hmset((tableName+"_"+dataMap.get(keyField)), dataMap);
|
||||
}
|
||||
jcp.sync();
|
||||
// }catch (Exception e) {
|
||||
// // TODO: handle exception
|
||||
// e.printStackTrace();
|
||||
// }
|
||||
long end=System.currentTimeMillis();
|
||||
jcp.close();
|
||||
jcp=null;
|
||||
logger.info("update maps end, cost:"+(end-start));
|
||||
}
|
||||
/**
|
||||
*
|
||||
* getMapById(获取Id 为xxxx的对象,返回一个Map)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param tableName
|
||||
* @param id
|
||||
* @return
|
||||
*Map<String,String>
|
||||
* @throws Exception
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public Map<String,String> getMapById(String tableName,long id) throws Exception{
|
||||
if(cluster==null){
|
||||
cluster=getJedisCluster();
|
||||
}
|
||||
Map<String, String> result=cluster.hgetAll(tableName+"_"+id);
|
||||
return result;
|
||||
}
|
||||
/**
|
||||
*
|
||||
* getMapById(获取Id 为xxxx的对象,返回一个Map)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param cluster
|
||||
* @param tableName
|
||||
* @param id
|
||||
* @return
|
||||
*Map<String,String>
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public Map<String,String> getMapById(JedisCluster cluster,String tableName,long id){
|
||||
Map<String, String> result=cluster.hgetAll(tableName+"_"+id);
|
||||
return result;
|
||||
}
|
||||
|
||||
public void saveList(List<String> jsonList,String sql,int expire) throws Exception{
|
||||
if(cluster==null)cluster=getJedisCluster();
|
||||
if(jcp==null)getJedisClusterPipeline();
|
||||
for(String json :jsonList){
|
||||
jcp.rpush(sql, json);
|
||||
}
|
||||
jcp.expire(sql, expire);
|
||||
jcp.sync();
|
||||
jcp.close();
|
||||
jcp=null;
|
||||
}
|
||||
/**
|
||||
*
|
||||
* getSet(获取redis中的一个set的全部成员)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param key
|
||||
* @return
|
||||
* @throws Exception
|
||||
*Set<String>
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public Set<String> getSet(String key) throws Exception{
|
||||
if(cluster==null)cluster=getJedisCluster();
|
||||
return cluster.smembers(key);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* saveSet(向一个set中添加成员)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param setName
|
||||
* @param values
|
||||
* @throws Exception
|
||||
*void
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public void saveSet(String setName,String ...values) throws Exception{
|
||||
if(cluster==null)cluster=getJedisCluster();
|
||||
if(jcp==null)getJedisClusterPipeline();
|
||||
for(String val:values){
|
||||
jcp.sadd(setName, val);
|
||||
}
|
||||
jcp.sync();
|
||||
jcp.close();
|
||||
jcp=null;
|
||||
}
|
||||
/**
|
||||
*
|
||||
* isExistsInSet(判断一个字符串是否是set的成员,可用于去重,验证唯一性)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param setName
|
||||
* @param value
|
||||
* @return
|
||||
* @throws Exception
|
||||
*boolean
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public boolean isExistsInSet(String setName,String value) throws Exception{
|
||||
if(cluster==null)cluster=getJedisCluster();
|
||||
return cluster.sismember(setName, value);
|
||||
}
|
||||
public List<String> getList(String sql,long start,long end) throws Exception{
|
||||
if(cluster==null){
|
||||
cluster=getJedisCluster();
|
||||
}
|
||||
List<String> data=cluster.lrange(sql, start, end);
|
||||
return data;
|
||||
}
|
||||
public void saveString(String key,String value,int expire) throws Exception{
|
||||
logger.info("save String start");
|
||||
long start=System.currentTimeMillis();
|
||||
if(cluster==null){
|
||||
cluster=getJedisCluster();
|
||||
}
|
||||
cluster.set(key, value);
|
||||
cluster.expire(key, expire);
|
||||
long end=System.currentTimeMillis();
|
||||
logger.info("save String end,cost:"+(end-start));
|
||||
}
|
||||
public String getString(String key) throws Exception{
|
||||
if(cluster==null){
|
||||
cluster=getJedisCluster();
|
||||
}
|
||||
return cluster.get(key);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* del(删除key)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param keys
|
||||
* @throws Exception
|
||||
*void
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public void del(String... keys) throws Exception{
|
||||
if(cluster==null){
|
||||
cluster=getJedisCluster();
|
||||
}
|
||||
cluster.del(keys);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* clearData(清空数据)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @throws Exception
|
||||
*void
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public void clearData() throws Exception{
|
||||
if(cluster==null){
|
||||
cluster=getJedisCluster();
|
||||
}
|
||||
logger.info("clear data start");
|
||||
long start=System.currentTimeMillis();
|
||||
Map<String, JedisPool> nodesMap=cluster.getClusterNodes();
|
||||
if(nodesMap==null){
|
||||
logger.error("empty redis nodes");
|
||||
return;
|
||||
}
|
||||
for(Entry<String, JedisPool> jedis:nodesMap.entrySet()){
|
||||
Jedis client=jedis.getValue().getResource();
|
||||
// only master node can flush db
|
||||
if(client.clusterInfo().indexOf("master")!=-1)
|
||||
client.flushAll();
|
||||
client.close();
|
||||
}
|
||||
long time=System.currentTimeMillis()-start;
|
||||
logger.info("clear data finish cost: "+time);
|
||||
}
|
||||
/**
|
||||
*
|
||||
* exists(键是否存在)
|
||||
* (这里描述这个方法适用条件 – 可选)
|
||||
* @param key
|
||||
* @return
|
||||
* @throws Exception
|
||||
*boolean
|
||||
* @exception
|
||||
* @since 1.0.0
|
||||
*/
|
||||
public boolean exists(String key) throws Exception{
|
||||
if(cluster==null){
|
||||
cluster=getJedisCluster();
|
||||
}
|
||||
return cluster.exists(key);
|
||||
}
|
||||
public static void main(String[] args) {
|
||||
|
||||
}
|
||||
}
|
||||
39
src/main/java/com/nis/util/redis/SaveRedisListThread.java
Normal file
39
src/main/java/com/nis/util/redis/SaveRedisListThread.java
Normal file
@@ -0,0 +1,39 @@
|
||||
package com.nis.util.redis;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.nis.web.service.SpringContextHolder;
|
||||
|
||||
public class SaveRedisListThread extends Thread {
|
||||
private static RedisDao redisDao = SpringContextHolder.getBean(RedisDao.class);
|
||||
protected final Logger logger = Logger.getLogger(this.getClass());
|
||||
|
||||
private String key;
|
||||
private List<String> value;
|
||||
private int expire;
|
||||
|
||||
public SaveRedisListThread(String key, List<String> value, int expire) {
|
||||
super(SaveRedisListThread.class.getSimpleName());
|
||||
this.key = key;
|
||||
this.value = value;
|
||||
this.expire = expire;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
redisDao.saveList(value, key, expire);
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
try {
|
||||
if (redisDao.exists(key)) {
|
||||
redisDao.del(key);
|
||||
}
|
||||
} catch (Exception e1) {
|
||||
logger.error(e1.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
42
src/main/java/com/nis/util/redis/SaveRedisThread.java
Normal file
42
src/main/java/com/nis/util/redis/SaveRedisThread.java
Normal file
@@ -0,0 +1,42 @@
|
||||
package com.nis.util.redis;
|
||||
import org.apache.log4j.Logger;
|
||||
|
||||
import com.nis.util.Constants;
|
||||
import com.nis.util.JsonMapper;
|
||||
import com.nis.util.redis.RedisDao;
|
||||
import com.nis.web.service.SpringContextHolder;
|
||||
|
||||
public class SaveRedisThread extends Thread {
|
||||
private static RedisDao redisDao = SpringContextHolder.getBean(RedisDao.class);
|
||||
protected final Logger logger = Logger.getLogger(this.getClass());
|
||||
|
||||
private String key;
|
||||
private Object value;
|
||||
private int expire;
|
||||
|
||||
public SaveRedisThread( String key, Object value,int expire){
|
||||
super(SaveRedisThread.class.getSimpleName());
|
||||
this.key = key;
|
||||
this.value = value;
|
||||
this.expire = expire;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void run() {
|
||||
try {
|
||||
logger.info("saveRedis开始--"+System.currentTimeMillis());
|
||||
redisDao.saveString(key, JsonMapper.toJsonString(value), expire);
|
||||
} catch (Exception e) {
|
||||
logger.error(e.getMessage());
|
||||
try {
|
||||
if(redisDao.exists(key)){
|
||||
redisDao.del(key);
|
||||
}
|
||||
} catch (Exception e1) {
|
||||
logger.error(e1.getMessage());
|
||||
}
|
||||
}finally {
|
||||
logger.info("saveRedis结束--"+System.currentTimeMillis());
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user