1
0
mirror of https://github.com/chatopera/cosin.git synced 2025-08-05 20:41:34 +08:00

Clean up MainUtils

This commit is contained in:
dengchao@xgtl 2020-04-16 14:52:10 +08:00
parent 1644826f5b
commit c45941540c
2 changed files with 1888 additions and 1988 deletions

View File

@ -37,6 +37,7 @@ import com.googlecode.aviator.AviatorEvaluator;
import freemarker.template.Configuration; import freemarker.template.Configuration;
import freemarker.template.TemplateException; import freemarker.template.TemplateException;
import io.netty.handler.codec.http.HttpHeaders; import io.netty.handler.codec.http.HttpHeaders;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails; import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.beanutils.BeanUtilsBean; import org.apache.commons.beanutils.BeanUtilsBean;
import org.apache.commons.beanutils.ConversionException; import org.apache.commons.beanutils.ConversionException;
@ -49,8 +50,6 @@ import org.jsoup.Jsoup;
import org.jsoup.nodes.Document; import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element; import org.jsoup.nodes.Element;
import org.jsoup.select.Elements; import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils; import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException; import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException; import org.springframework.beans.FatalBeanException;
@ -63,39 +62,39 @@ import java.beans.BeanInfo;
import java.beans.Introspector; import java.beans.Introspector;
import java.beans.PropertyDescriptor; import java.beans.PropertyDescriptor;
import java.io.*; import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Modifier; import java.lang.reflect.Modifier;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException; import java.text.ParseException;
import java.text.SimpleDateFormat; import java.text.SimpleDateFormat;
import java.util.*; import java.util.*;
import java.util.regex.Matcher; import java.util.regex.Matcher;
import java.util.regex.Pattern; import java.util.regex.Pattern;
@SuppressWarnings("unused")
@Slf4j
public class MainUtils { public class MainUtils {
private final static Logger logger = LoggerFactory.getLogger(MainUtils.class); private static final ObjectMapper JSON = new ObjectMapper();
private static final MD5 md5 = new MD5();
private static MD5 md5 = new MD5(); private static final Random random = new Random();
public static SimpleDateFormat dateFormate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); public static SimpleDateFormat dateFormate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd"); public static SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
public static SimpleDateFormat timeRangeDateFormat = new SimpleDateFormat("HH:mm"); public static SimpleDateFormat timeRangeDateFormat = new SimpleDateFormat("HH:mm");
static {
JSON.setSerializationInclusion(Include.NON_NULL);
JSON.configure(SerializationFeature.INDENT_OUTPUT, Boolean.TRUE);
}
/** /**
* 当前时间+已过随机生成的 长整形数字 * 当前时间+已过随机生成的 长整形数字
*
* @return
*/ */
public static String genID() { public static String genID() {
return Base62.encode(getUUID()).toLowerCase(); return Objects.requireNonNull(Base62.encode(getUUID())).toLowerCase();
} }
public static String genIDByKey(String key) { public static String genIDByKey(String key) {
return Base62.encode(key).toLowerCase(); return Objects.requireNonNull(Base62.encode(key)).toLowerCase();
} }
public static String getUUID() { public static String getUUID() {
@ -156,7 +155,7 @@ public class MainUtils {
public static long ipToLong(String ipAddress) { public static long ipToLong(String ipAddress) {
long result = 0; long result = 0;
String[] ipAddressInArray = ipAddress.split("\\."); String[] ipAddressInArray = ipAddress.split("\\.");
if (ipAddressInArray != null && ipAddressInArray.length == 4) { if (ipAddressInArray.length == 4) {
for (int i = 3; i >= 0; i--) { for (int i = 3; i >= 0; i--) {
long ip = Long.parseLong(ipAddressInArray[3 - i]); long ip = Long.parseLong(ipAddressInArray[3 - i]);
@ -181,12 +180,9 @@ public class MainUtils {
/*** /***
* ID编码 发送对话的时候使用 * ID编码 发送对话的时候使用
* @param id
* @param nid
* @return
*/ */
public static String genNewID(String id, String nid) { public static String genNewID(String id, String nid) {
StringBuffer strb = new StringBuffer(); StringBuilder strb = new StringBuilder();
if (id != null && nid != null) { if (id != null && nid != null) {
int length = Math.max(id.length(), nid.length()); int length = Math.max(id.length(), nid.length());
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
@ -203,12 +199,8 @@ public class MainUtils {
return strb.toString(); return strb.toString();
} }
/**
* @param request
* @return
*/
public static Map<String, Object> getRequestParam(HttpServletRequest request) { public static Map<String, Object> getRequestParam(HttpServletRequest request) {
Map<String, Object> values = new HashMap<String, Object>(); Map<String, Object> values = new HashMap<>();
Enumeration<String> enums = request.getParameterNames(); Enumeration<String> enums = request.getParameterNames();
while (enums.hasMoreElements()) { while (enums.hasMoreElements()) {
String param = enums.nextElement(); String param = enums.nextElement();
@ -218,15 +210,14 @@ public class MainUtils {
} }
/** /**
* @param request *
* @return
*/ */
public static String getParameter(HttpServletRequest request) { public static String getParameter(HttpServletRequest request) {
Enumeration<String> names = request.getParameterNames(); Enumeration<String> names = request.getParameterNames();
StringBuffer strb = new StringBuffer(); StringBuilder strb = new StringBuilder();
while (names.hasMoreElements()) { while (names.hasMoreElements()) {
String name = names.nextElement(); String name = names.nextElement();
if (name.indexOf("password") < 0) { //不记录 任何包含 password 的参数内容 if (!name.contains("password")) { //不记录 任何包含 password 的参数内容
if (strb.length() > 0) { if (strb.length() > 0) {
strb.append(","); strb.append(",");
} }
@ -239,8 +230,6 @@ public class MainUtils {
/** /**
* 获取一天的开始时间 * 获取一天的开始时间
*
* @return
*/ */
public static Date getStartTime() { public static Date getStartTime() {
Calendar todayStart = Calendar.getInstance(); Calendar todayStart = Calendar.getInstance();
@ -253,13 +242,11 @@ public class MainUtils {
/** /**
* 获取一天的开始时间 * 获取一天的开始时间
*
* @return
*/ */
public static Date getWeekStartTime() { public static Date getWeekStartTime() {
Calendar weekStart = Calendar.getInstance(); Calendar weekStart = Calendar.getInstance();
weekStart.set( weekStart.set(
weekStart.get(Calendar.YEAR), weekStart.get(Calendar.MONDAY), weekStart.get(Calendar.DAY_OF_MONTH), 0, weekStart.get(Calendar.YEAR), weekStart.get(Calendar.MONTH), weekStart.get(Calendar.DAY_OF_MONTH), 0,
0, 0); 0, 0);
weekStart.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY); weekStart.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
return weekStart.getTime(); return weekStart.getTime();
@ -267,8 +254,6 @@ public class MainUtils {
/** /**
* 获取一天的开始时间 * 获取一天的开始时间
*
* @return
*/ */
public static Date getLast30Day() { public static Date getLast30Day() {
Calendar todayStart = Calendar.getInstance(); Calendar todayStart = Calendar.getInstance();
@ -282,8 +267,6 @@ public class MainUtils {
/** /**
* 获取一天的开始时间 * 获取一天的开始时间
*
* @return
*/ */
public static Date getLastDay(int days) { public static Date getLastDay(int days) {
Calendar todayStart = Calendar.getInstance(); Calendar todayStart = Calendar.getInstance();
@ -297,8 +280,6 @@ public class MainUtils {
/** /**
* 获取一天的结束时间 * 获取一天的结束时间
*
* @return
*/ */
public static Date getEndTime() { public static Date getEndTime() {
Calendar todayEnd = Calendar.getInstance(); Calendar todayEnd = Calendar.getInstance();
@ -311,8 +292,6 @@ public class MainUtils {
/** /**
* 获取一天的结束时间 * 获取一天的结束时间
*
* @return
*/ */
public static Date getLastTime(int secs) { public static Date getLastTime(int secs) {
Calendar todayEnd = Calendar.getInstance(); Calendar todayEnd = Calendar.getInstance();
@ -335,34 +314,35 @@ public class MainUtils {
public static BrowserClient parseClient(HttpServletRequest request) { public static BrowserClient parseClient(HttpServletRequest request) {
BrowserClient client = new BrowserClient(); BrowserClient client = new BrowserClient();
String browserDetails = request.getHeader("User-Agent"); String browserDetails = request.getHeader("User-Agent");
String userAgent = browserDetails; String user = browserDetails.toLowerCase();
String user = userAgent.toLowerCase(); String os;
String os = "";
String browser = "", version = ""; String browser = "", version = "";
//=================OS======================= //=================OS=======================
if (userAgent.toLowerCase().indexOf("windows") >= 0) { if (user.contains("windows")) {
os = "windows"; os = "windows";
} else if (userAgent.toLowerCase().indexOf("mac") >= 0) { } else if (user.contains("mac")) {
os = "mac"; os = "mac";
} else if (userAgent.toLowerCase().indexOf("x11") >= 0) { } else if (user.contains("x11")) {
os = "unix"; os = "unix";
} else if (userAgent.toLowerCase().indexOf("android") >= 0) { } else if (user.contains("android")) {
os = "android"; os = "android";
} else if (userAgent.toLowerCase().indexOf("iphone") >= 0) { } else if (user.contains("iphone")) {
os = "iphone"; os = "iphone";
} else { } else {
os = "UnKnown"; os = "UnKnown";
} }
//===============Browser=========================== //===============Browser===========================
if (user.contains("qqbrowser")) { if (user.contains("qqbrowser")) {
browser = "QQBrowser"; browser = "QQBrowser";
} else if (user.contains("msie") || user.indexOf("rv:11") > -1) { } else if (user.contains("msie") || user.contains("rv:11")) {
if (user.indexOf("rv:11") >= 0) { if (user.contains("rv:11")) {
browser = "IE11"; browser = "IE11";
} else { } else {
String substring = userAgent.substring(userAgent.indexOf("MSIE")).split(";")[0]; String substring = browserDetails.substring(browserDetails.indexOf("MSIE")).split(";")[0];
browser = substring.split(" ")[0].replace("MSIE", "IE") + substring.split(" ")[1]; browser = substring.split(" ")[0].replace("MSIE", "IE") + substring.split(" ")[1];
} }
} else if (user.contains("trident")) { } else if (user.contains("trident")) {
@ -370,25 +350,24 @@ public class MainUtils {
} else if (user.contains("edge")) { } else if (user.contains("edge")) {
browser = "Edge"; browser = "Edge";
} else if (user.contains("safari") && user.contains("version")) { } else if (user.contains("safari") && user.contains("version")) {
browser = (userAgent.substring(userAgent.indexOf("Safari")).split(" ")[0]).split("/")[0]; browser = (browserDetails.substring(browserDetails.indexOf("Safari")).split(" ")[0]).split("/")[0];
version = (userAgent.substring(userAgent.indexOf("Version")).split(" ")[0]).split("/")[1]; version = (browserDetails.substring(browserDetails.indexOf("Version")).split(" ")[0]).split("/")[1];
} else if (user.contains("opr") || user.contains("opera")) { } else if (user.contains("opr") || user.contains("opera")) {
if (user.contains("opera")) { if (user.contains("opera")) {
browser = (userAgent.substring(userAgent.indexOf("Opera")).split(" ")[0]).split( browser = (browserDetails.substring(browserDetails.indexOf("Opera")).split(" ")[0]).split(
"/")[0] + "-" + (userAgent.substring(userAgent.indexOf("Version")).split(" ")[0]).split("/")[1]; "/")[0] + "-" + (browserDetails.substring(browserDetails.indexOf("Version")).split(" ")[0]).split("/")[1];
} else if (user.contains("opr")) { } else if (user.contains("opr")) {
browser = ((userAgent.substring(userAgent.indexOf("OPR")).split(" ")[0]).replace("/", "-")).replace( browser = ((browserDetails.substring(browserDetails.indexOf("OPR")).split(" ")[0]).replace("/", "-")).replace(
"OPR", "Opera"); "OPR", "Opera");
} }
} else if (user.contains("chrome")) { } else if (user.contains("chrome")) {
browser = "Chrome"; browser = "Chrome";
} else if ((user.indexOf("mozilla/7.0") > -1) || (user.indexOf("netscape6") != -1) || (user.indexOf( } else if (user.contains("mozilla/7.0") || user.contains("netscape6") || user.contains("mozilla/4.7") ||
"mozilla/4.7") != -1) || (user.indexOf("mozilla/4.78") != -1) || (user.indexOf( user.contains("mozilla/4.78") || user.contains("mozilla/4.08") || user.contains("mozilla/3")) {
"mozilla/4.08") != -1) || (user.indexOf("mozilla/3") != -1)) {
//browser=(userAgent.substring(userAgent.indexOf("MSIE")).split(" ")[0]).replace("/", "-"); //browser=(userAgent.substring(userAgent.indexOf("MSIE")).split(" ")[0]).replace("/", "-");
browser = "Netscape-?"; browser = "Netscape-?";
} else if ((user.indexOf("mozilla") > -1)) { } else if (user.contains("mozilla")) {
//browser=(userAgent.substring(userAgent.indexOf("MSIE")).split(" ")[0]).replace("/", "-"); //browser=(userAgent.substring(userAgent.indexOf("MSIE")).split(" ")[0]).replace("/", "-");
if (browserDetails.indexOf(" ") > 0) { if (browserDetails.indexOf(" ") > 0) {
browser = browserDetails.substring(0, browserDetails.indexOf(" ")); browser = browserDetails.substring(0, browserDetails.indexOf(" "));
@ -397,7 +376,7 @@ public class MainUtils {
} }
} else if (user.contains("firefox")) { } else if (user.contains("firefox")) {
browser = (userAgent.substring(userAgent.indexOf("Firefox")).split(" ")[0]).replace("/", "-"); browser = (browserDetails.substring(browserDetails.indexOf("Firefox")).split(" ")[0]).replace("/", "-");
} else if (user.contains("rv")) { } else if (user.contains("rv")) {
browser = "ie"; browser = "ie";
} else { } else {
@ -413,9 +392,6 @@ public class MainUtils {
/** /**
* 活动JPA统计结果 * 活动JPA统计结果
*
* @param values
* @return
*/ */
public static WebIMReport getWebIMReport(List<Object> values) { public static WebIMReport getWebIMReport(List<Object> values) {
WebIMReport report = new WebIMReport(); WebIMReport report = new WebIMReport();
@ -431,16 +407,12 @@ public class MainUtils {
/** /**
* 活动JPA统计结果 * 活动JPA统计结果
*
* @param values
* @return
*/ */
public static WebIMReport getWebIMInviteStatus(List<Object> values) { public static WebIMReport getWebIMInviteStatus(List<Object> values) {
WebIMReport report = new WebIMReport(); WebIMReport report = new WebIMReport();
if (values != null && values.size() > 0) { if (values != null && values.size() > 0) {
for (Object o : values) {
for (int i = 0; i < values.size(); i++) { Object[] value = (Object[]) o;
Object[] value = (Object[]) values.get(i);
if (value.length >= 2) { if (value.length >= 2) {
String invitestatus = (String) value[0]; String invitestatus = (String) value[0];
if (MainContext.OnlineUserInviteStatus.DEFAULT.toString().equals( if (MainContext.OnlineUserInviteStatus.DEFAULT.toString().equals(
@ -459,15 +431,12 @@ public class MainUtils {
/** /**
* 活动JPA统计结果 * 活动JPA统计结果
*
* @param values
* @return
*/ */
public static List<WebIMReport> getWebIMInviteAgg(List<Object> values) { public static List<WebIMReport> getWebIMInviteAgg(List<Object> values) {
List<WebIMReport> webIMReportList = new ArrayList<WebIMReport>(); List<WebIMReport> webIMReportList = new ArrayList<>();
if (values != null && values.size() > 0) { if (values != null && values.size() > 0) {
for (int i = 0; i < values.size(); i++) { for (Object o : values) {
Object[] value = (Object[]) values.get(i); Object[] value = (Object[]) o;
WebIMReport report = new WebIMReport(); WebIMReport report = new WebIMReport();
if (value.length == 3) { if (value.length == 3) {
report.setData((String) value[0]); report.setData((String) value[0]);
@ -482,15 +451,12 @@ public class MainUtils {
/** /**
* 活动JPA统计结果 * 活动JPA统计结果
*
* @param values
* @return
*/ */
public static List<WebIMReport> getWebIMDataAgg(List<Object> values) { public static List<WebIMReport> getWebIMDataAgg(List<Object> values) {
List<WebIMReport> webIMReportList = new ArrayList<WebIMReport>(); List<WebIMReport> webIMReportList = new ArrayList<>();
if (values != null && values.size() > 0) { if (values != null && values.size() > 0) {
for (int i = 0; i < values.size(); i++) { for (Object o : values) {
Object[] value = (Object[]) values.get(i); Object[] value = (Object[]) o;
WebIMReport report = new WebIMReport(); WebIMReport report = new WebIMReport();
if (value.length == 2) { if (value.length == 2) {
if (value[0] == null || value[0].toString().equalsIgnoreCase("null") || StringUtils.isBlank(value[0].toString())) { if (value[0] == null || value[0].toString().equalsIgnoreCase("null") || StringUtils.isBlank(value[0].toString())) {
@ -508,16 +474,12 @@ public class MainUtils {
/** /**
* 活动JPA统计结果 * 活动JPA统计结果
*
* @param values
* @return
*/ */
public static WebIMReport getWebIMInviteResult(List<Object> values) { public static WebIMReport getWebIMInviteResult(List<Object> values) {
WebIMReport report = new WebIMReport(); WebIMReport report = new WebIMReport();
if (values != null && values.size() > 0) { if (values != null && values.size() > 0) {
for (Object o : values) {
for (int i = 0; i < values.size(); i++) { Object[] value = (Object[]) o;
Object[] value = (Object[]) values.get(i);
if (value.length >= 2) { if (value.length >= 2) {
String invitestatus = (String) value[0]; String invitestatus = (String) value[0];
if (MainContext.OnlineUserInviteStatus.DEFAULT.toString().equals( if (MainContext.OnlineUserInviteStatus.DEFAULT.toString().equals(
@ -536,15 +498,12 @@ public class MainUtils {
/** /**
* 活动JPA统计结果 * 活动JPA统计结果
*
* @param values
* @return
*/ */
public static WeiXinReport getWeiXinReportResult(List<Object> values) { public static WeiXinReport getWeiXinReportResult(List<Object> values) {
WeiXinReport report = new WeiXinReport(); WeiXinReport report = new WeiXinReport();
if (values != null && values.size() > 0) { if (values != null && values.size() > 0) {
for (int i = 0; i < values.size(); i++) { for (Object o : values) {
Object[] value = (Object[]) values.get(i); Object[] value = (Object[]) o;
if (value.length >= 2) { if (value.length >= 2) {
String event = (String) value[0]; String event = (String) value[0];
if (MainContext.WeiXinEventType.SUB.toString().equals(event)) { if (MainContext.WeiXinEventType.SUB.toString().equals(event)) {
@ -563,7 +522,7 @@ public class MainUtils {
if (obj == null) { if (obj == null) {
return null; return null;
} }
Map<String, Object> map = new HashMap<String, Object>(); Map<String, Object> map = new HashMap<>();
try { try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
@ -593,9 +552,9 @@ public class MainUtils {
} }
public static void populate(Object bean, Map<Object, Object> properties) throws IllegalAccessException, InvocationTargetException { public static void populate(Object bean, Map<String, Object> properties) {
//noinspection unchecked
ConvertUtils.register(new Converter() { ConvertUtils.register(new Converter() {
@SuppressWarnings("rawtypes")
@Override @Override
public Object convert(Class arg0, Object arg1) { public Object convert(Class arg0, Object arg1) {
if (arg1 == null) { if (arg1 == null) {
@ -645,30 +604,21 @@ public class MainUtils {
return objectInput.readObject(); return objectInput.readObject();
} }
/**
* @param str public static String encryption(final String str) {
* @return
* @throws NoSuchAlgorithmException
*/
public static String encryption(final String str) throws NoSuchAlgorithmException {
BasicTextEncryptor textEncryptor = new BasicTextEncryptor(); BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
textEncryptor.setPassword(MainContext.getSystemSecrityPassword()); textEncryptor.setPassword(MainContext.getSystemSecrityPassword());
return textEncryptor.encrypt(str); return textEncryptor.encrypt(str);
} }
/** public static String decryption(final String str) {
* @param str
* @return
* @throws NoSuchAlgorithmException
*/
public static String decryption(final String str) throws NoSuchAlgorithmException {
BasicTextEncryptor textEncryptor = new BasicTextEncryptor(); BasicTextEncryptor textEncryptor = new BasicTextEncryptor();
textEncryptor.setPassword(MainContext.getSystemSecrityPassword()); textEncryptor.setPassword(MainContext.getSystemSecrityPassword());
return textEncryptor.decrypt(str); return textEncryptor.decrypt(str);
} }
public static String getTopic(final String snsid, final String msgtype, final String eventype, final String eventkey, final String msg) { public static String getTopic(final String snsid, final String msgtype, final String eventype, final String eventkey, final String msg) {
StringBuffer strb = new StringBuffer(); StringBuilder strb = new StringBuilder();
strb.append(snsid); strb.append(snsid);
strb.append(".").append(msgtype); strb.append(".").append(msgtype);
if (msgtype.equals("text")) { if (msgtype.equals("text")) {
@ -685,7 +635,7 @@ public class MainUtils {
} }
public static String getTopic(String snsid, String msgtype, String eventype) { public static String getTopic(String snsid, String msgtype, String eventype) {
StringBuffer strb = new StringBuffer(); StringBuilder strb = new StringBuilder();
strb.append(snsid); strb.append(snsid);
strb.append(".").append(msgtype); strb.append(".").append(msgtype);
if (msgtype.equals("text")) { if (msgtype.equals("text")) {
@ -700,16 +650,13 @@ public class MainUtils {
/** /**
* 处理 对话消息中的图片 * 处理 对话消息中的图片
*
* @param message
* @return
*/ */
public static String filterChatMessage(String message) { public static String filterChatMessage(String message) {
Document document = Jsoup.parse(message); Document document = Jsoup.parse(message);
Elements pngs = document.select("img[src]"); Elements pngs = document.select("img[src]");
for (Element element : pngs) { for (Element element : pngs) {
String imgUrl = element.attr("src"); String imgUrl = element.attr("src");
if (imgUrl.indexOf("/res/image") >= 0) { if (imgUrl.contains("/res/image")) {
element.attr("class", "ukefu-media-image"); element.attr("class", "ukefu-media-image");
} }
} }
@ -718,9 +665,6 @@ public class MainUtils {
/** /**
* 检查当前时间是否是在 时间范围内 时间范围的格式为 08:30~11:30,13:30~17:30 * 检查当前时间是否是在 时间范围内 时间范围的格式为 08:30~11:30,13:30~17:30
*
* @param timeRanges
* @return
*/ */
public static boolean isInWorkingHours(String timeRanges) { public static boolean isInWorkingHours(String timeRanges) {
boolean workintTime = true; boolean workintTime = true;
@ -746,22 +690,20 @@ public class MainUtils {
return workintTime; return workintTime;
} }
public static File processImage(final File destFile, final File imageFile) throws IOException { public static void processImage(final File destFile, final File imageFile) throws IOException {
if (imageFile != null && imageFile.exists()) { if (imageFile != null && imageFile.exists()) {
Thumbnails.of(imageFile).width(460).keepAspectRatio(true).toFile(destFile); Thumbnails.of(imageFile).width(460).keepAspectRatio(true).toFile(destFile);
} }
return destFile;
} }
public static File scaleImage(final File destFile, final File imageFile, float quality) throws IOException { public static void scaleImage(final File destFile, final File imageFile, float quality) throws IOException {
if (imageFile != null && imageFile.exists()) { if (imageFile != null && imageFile.exists()) {
Thumbnails.of(imageFile).scale(1f).outputQuality(quality).toFile(destFile); Thumbnails.of(imageFile).scale(1f).outputQuality(quality).toFile(destFile);
} }
return destFile;
} }
public static String processEmoti(String message) { public static String processEmoti(String message) {
Pattern pattern = Pattern.compile("\\[([\\d]*?)\\]"); Pattern pattern = Pattern.compile("\\[([\\d]*?)]");
SystemConfig systemConfig = MainContext.getCache().findOneSystemByIdAndOrgi( SystemConfig systemConfig = MainContext.getCache().findOneSystemByIdAndOrgi(
"systemConfig", MainContext.SYSTEM_ORGI); "systemConfig", MainContext.SYSTEM_ORGI);
@ -814,7 +756,7 @@ public class MainUtils {
} }
public static boolean secConfirm(SecretRepository secRes, String orgi, String confirm) { public static boolean secConfirm(SecretRepository secRes, String orgi, String confirm) {
/** /*
* 先调用 IMServer * 先调用 IMServer
*/ */
boolean execute = false; boolean execute = false;
@ -834,8 +776,6 @@ public class MainUtils {
/** /**
* 获取系统配置 * 获取系统配置
*
* @return
*/ */
public static SystemConfig getSystemConfig() { public static SystemConfig getSystemConfig() {
SystemConfig systemConfig = MainContext.getCache().findOneSystemByIdAndOrgi( SystemConfig systemConfig = MainContext.getCache().findOneSystemByIdAndOrgi(
@ -849,8 +789,6 @@ public class MainUtils {
/** /**
* 初始化呼叫中心功能里需要隐藏号码的字段 * 初始化呼叫中心功能里需要隐藏号码的字段
*
* @param tpRes
*/ */
public static void initSystemSecField(TablePropertiesRepository tpRes) { public static void initSystemSecField(TablePropertiesRepository tpRes) {
if (tpRes != null) { if (tpRes != null) {
@ -862,8 +800,6 @@ public class MainUtils {
/** /**
* 获取系统地区配置 * 获取系统地区配置
*
* @return
*/ */
public static void initSystemArea() { public static void initSystemArea() {
MainContext.getCache().deleteSystembyIdAndOrgi(Constants.CSKEFU_SYSTEM_AREA, MainContext.SYSTEM_ORGI); MainContext.getCache().deleteSystembyIdAndOrgi(Constants.CSKEFU_SYSTEM_AREA, MainContext.SYSTEM_ORGI);
@ -874,8 +810,6 @@ public class MainUtils {
/** /**
* 缓存 广告位 * 缓存 广告位
*
* @return
*/ */
public static void initAdv(String orgi) { public static void initAdv(String orgi) {
MainContext.getCache().deleteSystembyIdAndOrgi(Constants.CSKEFU_SYSTEM_ADV + "_" + orgi, orgi); MainContext.getCache().deleteSystembyIdAndOrgi(Constants.CSKEFU_SYSTEM_ADV + "_" + orgi, orgi);
@ -885,7 +819,7 @@ public class MainUtils {
} }
public static Template getTemplate(String id) { public static Template getTemplate(String id) {
Template templet = null; Template templet;
if ((templet = MainContext.getCache().findOneSystemByIdAndOrgi(id, MainContext.SYSTEM_ORGI)) == null) { if ((templet = MainContext.getCache().findOneSystemByIdAndOrgi(id, MainContext.SYSTEM_ORGI)) == null) {
TemplateRepository templateRes = MainContext.getContext().getBean(TemplateRepository.class); TemplateRepository templateRes = MainContext.getContext().getBean(TemplateRepository.class);
templet = templateRes.findByIdAndOrgi(id, MainContext.SYSTEM_ORGI); templet = templateRes.findByIdAndOrgi(id, MainContext.SYSTEM_ORGI);
@ -896,13 +830,9 @@ public class MainUtils {
/** /**
* 按照权重获取广告 * 按照权重获取广告
*
* @param adpos
* @return
*/ */
@SuppressWarnings("unchecked")
public static AdType getPointAdv(String adpos, String orgi) { public static AdType getPointAdv(String adpos, String orgi) {
List<AdType> adTypeList = new ArrayList<AdType>(); List<AdType> adTypeList = new ArrayList<>();
List<AdType> cacheAdTypeList = MainContext.getCache().findOneSystemListByIdAndOrgi( List<AdType> cacheAdTypeList = MainContext.getCache().findOneSystemListByIdAndOrgi(
Constants.CSKEFU_SYSTEM_ADV + "_" + orgi, orgi); Constants.CSKEFU_SYSTEM_ADV + "_" + orgi, orgi);
if (cacheAdTypeList == null) { if (cacheAdTypeList == null) {
@ -921,7 +851,7 @@ public class MainUtils {
} }
} }
} }
if (adTypeList != null && sysDic != null) { if (sysDic != null) {
for (AdType adType : cacheAdTypeList) { for (AdType adType : cacheAdTypeList) {
if (adType.getAdpos().equals(sysDic.getId())) { if (adType.getAdpos().equals(sysDic.getId())) {
adTypeList.add(adType); adTypeList.add(adType);
@ -931,13 +861,8 @@ public class MainUtils {
return weitht(adTypeList); return weitht(adTypeList);
} }
private static Random random = new Random();
/** /**
* 按照权重获取广告内容 * 按照权重获取广告内容
*
* @param adList
* @return
*/ */
private static AdType weitht(List<AdType> adList) { private static AdType weitht(List<AdType> adList) {
AdType adType = null; AdType adType = null;
@ -960,30 +885,24 @@ public class MainUtils {
/** /**
* 16进制字符串转换为字符串 * 16进制字符串转换为字符串
*
* @return
*/ */
public static String string2HexString(String strPart) { public static String string2HexString(String strPart) {
StringBuffer hexString = new StringBuffer(); StringBuilder hexString = new StringBuilder();
for (int i = 0; i < strPart.length(); i++) { for (int i = 0; i < strPart.length(); i++) {
int ch = (int) strPart.charAt(i); int ch = strPart.charAt(i);
String strHex = Integer.toHexString(ch); String strHex = Integer.toHexString(ch);
hexString.append(strHex); hexString.append(strHex);
} }
return hexString.toString(); return hexString.toString();
} }
/**
* @throws IOException
* @throws TemplateException
*/
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
public static String getTemplet(String templet, Map<String, Object> values) throws IOException, TemplateException { public static String getTemplet(String templet, Map<String, Object> values) throws IOException, TemplateException {
StringWriter writer = new StringWriter(); StringWriter writer = new StringWriter();
Configuration cfg = null; Configuration cfg;
freemarker.template.Template template = null; freemarker.template.Template template;
String retValue = templet; String retValue = templet;
if (templet != null && templet.length() > 0 && templet.indexOf("$") >= 0) { if (templet != null && templet.length() > 0 && templet.contains("$")) {
cfg = new Configuration(); cfg = new Configuration();
TempletLoader loader = new TempletLoader(templet); TempletLoader loader = new TempletLoader(templet);
cfg.setTemplateLoader(loader); cfg.setTemplateLoader(loader);
@ -997,12 +916,6 @@ public class MainUtils {
/** /**
* 发送邮件 * 发送邮件
*
* @param email
* @param cc
* @param subject
* @param content
* @throws Exception
*/ */
public static void sendMail(String email, String cc, String subject, String content, List<String> filenames) throws Exception { public static void sendMail(String email, String cc, String subject, String content, List<String> filenames) throws Exception {
SystemConfig config = MainUtils.getSystemConfig(); SystemConfig config = MainUtils.getSystemConfig();
@ -1028,24 +941,19 @@ public class MainUtils {
return null; return null;
} }
public static String processContentEncode(String str) throws Exception { public static String processContentEncode(String str) {
return Base64.encodeBase64String(str.getBytes(StandardCharsets.UTF_8)).replaceAll("\\+", "-"); return Base64.encodeBase64String(str.getBytes(StandardCharsets.UTF_8)).replaceAll("\\+", "-");
} }
public static String processContentDecode(String str) throws Exception { public static String processContentDecode(String str) {
return new String(Base64.decodeBase64(str.replaceAll("-", "\\+").getBytes()), StandardCharsets.UTF_8); return new String(Base64.decodeBase64(str.replaceAll("-", "\\+").getBytes()), StandardCharsets.UTF_8);
} }
/**
* @param defaultFormatValue
* @param text
* @return
*/
public static String processParam(String defaultFormatValue, String text) { public static String processParam(String defaultFormatValue, String text) {
String formatValue = "yyyy-MM-dd"; String formatValue = "yyyy-MM-dd";
if (text.matches("[ ]{0,}([Yy]{1,})[ ]{0,}[+-]{0,1}([\\d]{0,})")) { if (text.matches("[ ]*([Yy]+)[ ]*[+-]?([\\d]*)")) {
formatValue = "yyyy"; formatValue = "yyyy";
} else if (text.matches("[ ]{0,}([Mm]{1,})[ ]{0,}[+-]{0,1}([\\d]{0,})")) { } else if (text.matches("[ ]*([Mm]+)[ ]*[+-]?([\\d]*)")) {
formatValue = "yyyy-MM"; formatValue = "yyyy-MM";
} }
@ -1055,13 +963,10 @@ public class MainUtils {
/*** /***
* 计算T+1 * 计算T+1
* @param text
* @param format
* @return
*/ */
public static String getDays(String text, String format) { public static String getDays(String text, String format) {
String retDateFormat = text; String retDateFormat = text;
Pattern pattern = Pattern.compile("[ ]{0,}([TtMmYy]{1,})[ ]{0,}[+-]{0,1}([\\d]{0,})"); Pattern pattern = Pattern.compile("[ ]*([TtMmYy]+)[ ]*[+-]?([\\d]*)");
Matcher matcher = pattern.matcher(text); Matcher matcher = pattern.matcher(text);
if (matcher.find() && matcher.groupCount() >= 1) { if (matcher.find() && matcher.groupCount() >= 1) {
try { try {
@ -1081,11 +986,9 @@ public class MainUtils {
/*** /***
* 计算T+1 * 计算T+1
* @param text
* @return
*/ */
public static Object getDaysParam(String text) { public static Object getDaysParam(String text) {
Map<String, Object> context = new HashMap<String, Object>(); Map<String, Object> context = new HashMap<>();
context.put("T", processDays()); context.put("T", processDays());
context.put("t", processDays()); context.put("t", processDays());
context.put("M", processMonth()); context.put("M", processMonth());
@ -1096,13 +999,7 @@ public class MainUtils {
return AviatorEvaluator.execute(text, context); return AviatorEvaluator.execute(text, context);
} }
/** public static String formatDateValue(String format, Object value) {
* @param value
* @return
* @throws ParseException
* @throws Exception
*/
public static String formatDateValue(String format, Object value) throws ParseException {
if (value != null && value.toString().matches("[\\d.]{5,}")) { if (value != null && value.toString().matches("[\\d.]{5,}")) {
value = new SimpleDateFormat(format).format( value = new SimpleDateFormat(format).format(
new Date((long) (Double.parseDouble(value.toString()) * 24 * 60 * 60 * 1000))); new Date((long) (Double.parseDouble(value.toString()) * 24 * 60 * 60 * 1000)));
@ -1110,17 +1007,11 @@ public class MainUtils {
return value != null ? value.toString() : "0"; return value != null ? value.toString() : "0";
} }
/**
* @param value
* @return
* @throws ParseException
* @throws Exception
*/
public static String formatMonthValue(String formatValue, Object value) throws ParseException { public static String formatMonthValue(String formatValue, Object value) throws ParseException {
if (value != null && value.toString().matches("[\\d.]{3,}")) { if (value != null && value.toString().matches("[\\d.]{3,}")) {
int months = (int) Double.parseDouble(String.valueOf(value)); int months = (int) Double.parseDouble(String.valueOf(value));
int year = 0; int year;
int month = 0; int month;
if (months % 12 == 0) { if (months % 12 == 0) {
year = months / 12 - 1; year = months / 12 - 1;
month = 12; month = 12;
@ -1139,36 +1030,19 @@ public class MainUtils {
return value != null ? value.toString() : "0"; return value != null ? value.toString() : "0";
} }
/**
* @return
*/
public static double processDays() { public static double processDays() {
return System.currentTimeMillis() * 1.0f / (1000 * 60 * 60 * 24); return System.currentTimeMillis() * 1.0f / (1000 * 60 * 60 * 24);
} }
/**
* @return
*/
public static double processMonth() { public static double processMonth() {
Calendar calendar = Calendar.getInstance(); Calendar calendar = Calendar.getInstance();
int month = calendar.get(Calendar.YEAR) * 12 + calendar.get(Calendar.MONTH) + 1; return calendar.get(Calendar.YEAR) * 12 + calendar.get(Calendar.MONTH) + 1;
return month;
} }
/**
* @return
*/
public static double processYear() { public static double processYear() {
return Calendar.getInstance().get(Calendar.YEAR); return Calendar.getInstance().get(Calendar.YEAR);
} }
private static final ObjectMapper JSON = new ObjectMapper();
static {
JSON.setSerializationInclusion(Include.NON_NULL);
JSON.configure(SerializationFeature.INDENT_OUTPUT, Boolean.TRUE);
}
public static String toJson(Object obj) { public static String toJson(Object obj) {
try { try {
return JSON.writeValueAsString(obj); return JSON.writeValueAsString(obj);
@ -1179,12 +1053,9 @@ public class MainUtils {
return null; return null;
} }
/**
* @param message
*/
public static AsrResult parseAsrResult(String id, String message, int speakms) { public static AsrResult parseAsrResult(String id, String message, int speakms) {
AsrResult asrResult = null; AsrResult asrResult = null;
Pattern pattern = Pattern.compile("([\\d]{1,})[\\.]{1}([\\s\\S]*);"); Pattern pattern = Pattern.compile("([\\d]+)[.]([\\s\\S]*);");
Matcher matcher = pattern.matcher(message); Matcher matcher = pattern.matcher(message);
if (matcher.find() && matcher.groupCount() == 2) { if (matcher.find() && matcher.groupCount() == 2) {
asrResult = new AsrResult(id, matcher.group(2), matcher.group(1)); asrResult = new AsrResult(id, matcher.group(2), matcher.group(1));
@ -1200,13 +1071,6 @@ public class MainUtils {
/** /**
* 发送短信 * 发送短信
*
* @param phone
* @param id
* @param tpId
* @param tplValuesMap
* @return
* @throws Exception
*/ */
public static boolean sendSms(String phone, String id, String tpId, Map<String, Object> tplValuesMap) throws Exception { public static boolean sendSms(String phone, String id, String tpId, Map<String, Object> tplValuesMap) throws Exception {
SystemConfig config = MainUtils.getSystemConfig(); SystemConfig config = MainUtils.getSystemConfig();
@ -1237,12 +1101,12 @@ public class MainUtils {
//初始化ascClient,暂时不支持多region请勿修改 //初始化ascClient,暂时不支持多region请勿修改
IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId, IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou", accessKeyId,
accessKeySecret); accessKeySecret);
DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product, domain); DefaultProfile.addEndpoint("cn-hangzhou", product, domain);
IAcsClient acsClient = new DefaultAcsClient(profile); IAcsClient acsClient = new DefaultAcsClient(profile);
//组装请求对象 //组装请求对象
SendSmsRequest request = new SendSmsRequest(); SendSmsRequest request = new SendSmsRequest();
//使用post提交 //使用post提交
request.setMethod(MethodType.POST); request.setSysMethod(MethodType.POST);
//必填:待发送手机号支持以逗号分隔的形式进行批量调用批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式 //必填:待发送手机号支持以逗号分隔的形式进行批量调用批量上限为1000个手机号码,批量调用相对于单条调用及时性稍有延迟,验证码类型的短信推荐使用单条调用的方式
request.setPhoneNumbers(phone); request.setPhoneNumbers(phone);
//必填:短信签名-可在短信控制台中找到 //必填:短信签名-可在短信控制台中找到
@ -1272,15 +1136,6 @@ public class MainUtils {
return false; return false;
} }
/**
* @param userid
* @param client
* @param session
* @param orgi
* @param ipaddr
* @param hostname
* @return
*/
public static WorkSession createWorkSession(String userid, String client, String session, String orgi, String ipaddr, String hostname, String admin, boolean first) { public static WorkSession createWorkSession(String userid, String client, String session, String orgi, String ipaddr, String hostname, String admin, boolean first) {
WorkSession workSession = new WorkSession(); WorkSession workSession = new WorkSession();
workSession.setCreatetime(new Date()); workSession.setCreatetime(new Date());
@ -1306,44 +1161,33 @@ public class MainUtils {
return workSession; return workSession;
} }
/**
* @param plan
* @return
*/
public static String convertCrond(JobTask plan) { public static String convertCrond(JobTask plan) {
StringBuffer strb = new StringBuffer(); StringBuilder strb = new StringBuilder();
if ("day".equals(plan.getRunCycle())) {
strb.append(plan.getRunBeginSecond()).append(" ").append(plan.getRunBeginMinute()).append( strb.append(plan.getRunBeginSecond()).append(" ").append(plan.getRunBeginMinute()).append(
plan.getIsRepeat() && plan.getRepeatSpace() != null && plan.getRepeatSpace() < 60 ? "/" + plan.getRepeatSpace() : "").append( plan.getIsRepeat() && plan.getRepeatSpace() != null && plan.getRepeatSpace() < 60 ? "/" + plan.getRepeatSpace() : "").append(
" ").append(plan.getRunBeginHour()).append( " ").append(plan.getRunBeginHour()).append(
plan.getIsRepeat() && plan.getRepeatSpace() != null && plan.getRepeatSpace() > 60 ? "/" + plan.getRepeatSpace() / 60 : (plan.getRepeatJustTime() != null && plan.getRepeatJustTime() > 0 ? "-" + (plan.getRunBeginHour() + plan.getRepeatJustTime()) : "")).append( plan.getIsRepeat() && plan.getRepeatSpace() != null && plan.getRepeatSpace() > 60 ? "/" + plan.getRepeatSpace() / 60 : (plan.getRepeatJustTime() != null && plan.getRepeatJustTime() > 0 ? "-" + (plan.getRunBeginHour() + plan.getRepeatJustTime()) : "")).append(
" ").append("*").append( " ");
if ("day".equals(plan.getRunCycle())) {
strb.append("*").append(
plan.getRunSpace() != null && plan.getRunSpace() > 0 ? "/" + plan.getRunSpace() : "").append( plan.getRunSpace() != null && plan.getRunSpace() > 0 ? "/" + plan.getRunSpace() : "").append(
" ").append(" * ?"); " ").append(" * ?");
} }
if ("week".equals(plan.getRunCycle())) { if ("week".equals(plan.getRunCycle())) {
strb.append(plan.getRunBeginSecond()).append(" ").append(plan.getRunBeginMinute()).append( strb.append(plan.getRunDates() == null || plan.getRunDates().length == 0 ? "*" : "?").append(
plan.getIsRepeat() && plan.getRepeatSpace() != null && plan.getRepeatSpace() < 60 ? "/" + plan.getRepeatSpace() : "").append(
" ").append(plan.getRunBeginHour()).append(
plan.getIsRepeat() && plan.getRepeatSpace() != null && plan.getRepeatSpace() > 60 ? "/" + plan.getRepeatSpace() / 60 : (plan.getRepeatJustTime() != null && plan.getRepeatJustTime() > 0 ? "-" + (plan.getRunBeginHour() + plan.getRepeatJustTime()) : "")).append(
" ").append(plan.getRunDates() == null || plan.getRunDates().length == 0 ? "*" : "?").append(
" * ").append(plan.getRunDates() == null || plan.getRunDates().length == 0 ? "?" : StringUtils.join( " * ").append(plan.getRunDates() == null || plan.getRunDates().length == 0 ? "?" : StringUtils.join(
plan.getRunDates(), ",")).append( plan.getRunDates(), ",")).append(
plan.getRunSpace() != null && plan.getRunSpace() > 0 ? "/" + plan.getRunSpace() : ""); plan.getRunSpace() != null && plan.getRunSpace() > 0 ? "/" + plan.getRunSpace() : "");
} }
if ("month".equals(plan.getRunCycle())) { if ("month".equals(plan.getRunCycle())) {
strb.append(plan.getRunBeginSecond()).append(" ").append(plan.getRunBeginMinute()).append( strb.append(plan.getRunBeginDate()).append(" ").append(
plan.getIsRepeat() && plan.getRepeatSpace() != null && plan.getRepeatSpace() < 60 ? "/" + plan.getRepeatSpace() : "").append(
" ").append(plan.getRunBeginHour()).append(
plan.getIsRepeat() && plan.getRepeatSpace() != null && plan.getRepeatSpace() > 60 ? "/" + plan.getRepeatSpace() / 60 : (plan.getRepeatJustTime() != null && plan.getRepeatJustTime() > 0 ? "-" + (plan.getRunBeginHour() + plan.getRepeatJustTime()) : "")).append(
" ").append(plan.getRunBeginDate()).append(" ").append(
plan.getRunDates() == null || plan.getRunDates().length == 0 ? "*" : StringUtils.join( plan.getRunDates() == null || plan.getRunDates().length == 0 ? "*" : StringUtils.join(
plan.getRunDates(), ",")).append(" ").append(" ?"); plan.getRunDates(), ",")).append(" ").append(" ?");
} }
return strb.toString(); return strb.toString();
} }
public static Date updateTaskNextFireTime(JobDetail jobDetail) throws Exception { public static Date updateTaskNextFireTime(JobDetail jobDetail) {
Date nextFireDate = new Date(); Date nextFireDate = new Date();
Date date = new Date(); Date date = new Date();
if (jobDetail != null && jobDetail.getCronexp() != null && jobDetail.getCronexp().length() > 0) { if (jobDetail != null && jobDetail.getCronexp() != null && jobDetail.getCronexp().length() > 0) {
@ -1360,37 +1204,33 @@ public class MainUtils {
return nextFireDate; return nextFireDate;
} }
/**
* @param dialNum
* @param distype
* @return
*/
public static String processSecField(String dialNum, String distype) { public static String processSecField(String dialNum, String distype) {
StringBuilder strb = new StringBuilder(dialNum); StringBuilder strb = new StringBuilder(dialNum);
if (distype.equals("01")) { switch (distype) {
case "01":
if (strb.length() > 4) { if (strb.length() > 4) {
strb.replace(strb.length() / 2 - 2, strb.length() / 2 + 2, "****"); strb.replace(strb.length() / 2 - 2, strb.length() / 2 + 2, "****");
} else { } else {
strb.replace(0, strb.length(), "****"); strb.replace(0, strb.length(), "****");
} }
} else if (distype.equals("02")) { break;
case "02":
if (strb.length() > 4) { if (strb.length() > 4) {
strb.replace(strb.length() - 4, strb.length(), "****"); strb.replace(strb.length() - 4, strb.length(), "****");
} else { } else {
strb.replace(0, strb.length(), "****"); strb.replace(0, strb.length(), "****");
} }
} else if (distype.equals("03")) { break;
if (strb.length() > 4) { case "03":
strb.replace(0, 4, "****"); strb.replace(0, Math.min(strb.length(), 4), "****");
} else { break;
strb.replace(0, strb.length(), "****"); case "04":
}
} else if (distype.equals("04")) {
int length = strb.length(); int length = strb.length();
strb.setLength(0); strb.setLength(0);
for (int i = 0; i < length; i++) { for (int i = 0; i < length; i++) {
strb.append("*"); strb.append("*");
} }
break;
} }
return strb.toString(); return strb.toString();
} }
@ -1398,8 +1238,8 @@ public class MainUtils {
public static void putMapEntry( public static void putMapEntry(
Map<String, String[]> map, String name, Map<String, String[]> map, String name,
String value) { String value) {
String[] newValues = null; String[] newValues;
String[] oldValues = (String[]) (String[]) map.get(name); String[] oldValues = map.get(name);
if (oldValues == null) { if (oldValues == null) {
newValues = new String[1]; newValues = new String[1];
newValues[0] = value; newValues[0] = value;

View File

@ -49,11 +49,12 @@ import java.util.List;
import java.util.Map; import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
public class ExcelImportProecess extends DataProcess{ public class ExcelImportProecess extends DataProcess {
private DecimalFormat format = new DecimalFormat("###"); private final DecimalFormat format = new DecimalFormat("###");
private AtomicInteger pages = new AtomicInteger() , errors = new AtomicInteger(); private final AtomicInteger pages = new AtomicInteger();
private final AtomicInteger errors = new AtomicInteger();
public ExcelImportProecess(DSDataEvent event){ public ExcelImportProecess(DSDataEvent event) {
super(event); super(event);
} }
@ -62,12 +63,12 @@ public class ExcelImportProecess extends DataProcess{
processExcel(event); processExcel(event);
} }
@SuppressWarnings({ "unchecked", "rawtypes" }) @SuppressWarnings({"unchecked", "rawtypes"})
private void processExcel(final DSDataEvent event){ private void processExcel(final DSDataEvent event) {
InputStream is = null; InputStream is = null;
try { try {
event.getDSData().getReport().setTableid(event.getDSData().getTask().getId()); event.getDSData().getReport().setTableid(event.getDSData().getTask().getId());
if(event.getDSData().getUser()!=null){ if (event.getDSData().getUser() != null) {
event.getDSData().getReport().setUserid(event.getDSData().getUser().getId()); event.getDSData().getReport().setUserid(event.getDSData().getUser().getId());
event.getDSData().getReport().setUsername(event.getDSData().getUser().getUsername()); event.getDSData().getReport().setUsername(event.getDSData().getUser().getUsername());
} }
@ -93,115 +94,122 @@ public class ExcelImportProecess extends DataProcess{
Row valueRow = sheet.getRow(1); Row valueRow = sheet.getRow(1);
int totalRows = sheet.getPhysicalNumberOfRows(); int totalRows = sheet.getPhysicalNumberOfRows();
int colNum = titleRow.getPhysicalNumberOfCells(); int colNum = titleRow.getPhysicalNumberOfCells();
for(int i=2 ; i<totalRows && valueRow == null ; i++){ for (int i = 2; i < totalRows && valueRow == null; i++) {
valueRow = sheet.getRow(i); valueRow = sheet.getRow(i);
if(valueRow !=null){ if (valueRow != null) {
break ; break;
} }
} }
/** /**
* 需要检查Mapping 是否存在 * 需要检查Mapping 是否存在
*/ */
long start = System.currentTimeMillis() ; long start = System.currentTimeMillis();
Map<Object, List> refValues = new HashMap<Object , List>() ; Map<Object, List> refValues = new HashMap<Object, List>();
MetadataTable table = event.getDSData().getTask() ; MetadataTable table = event.getDSData().getTask();
for(TableProperties tp : table.getTableproperty()){ for (TableProperties tp : table.getTableproperty()) {
if(tp.isReffk() && !StringUtils.isBlank(tp.getReftbid())){ if (tp.isReffk() && !StringUtils.isBlank(tp.getReftbid())) {
DataExchangeInterface exchange = (DataExchangeInterface) MainContext.getContext().getBean(tp.getReftbid()) ; DataExchangeInterface exchange = (DataExchangeInterface) MainContext.getContext().getBean(tp.getReftbid());
refValues.put(tp.getFieldname(), exchange.getListDataByIdAndOrgi(null, null, event.getOrgi())) ; refValues.put(tp.getFieldname(), exchange.getListDataByIdAndOrgi(null, null, event.getOrgi()));
} }
} }
for(int i=1 ; i<totalRows; i++){ for (int i = 1; i < totalRows; i++) {
Row row = sheet.getRow(i) ; Row row = sheet.getRow(i);
Object data = null ; Object data = null;
if(row!=null){ if (row != null) {
if(event.getDSData().getClazz() != null) { if (event.getDSData().getClazz() != null) {
data = event.getDSData().getClazz().newInstance() ; data = event.getDSData().getClazz().newInstance();
} }
Map<Object, Object> values = new HashMap<Object , Object>() ; Map<String, Object> values = new HashMap<>();
ArrayListMultimap<String, Object> multiValues = ArrayListMultimap.create(); ArrayListMultimap<String, Object> multiValues = ArrayListMultimap.create();
boolean skipDataVal = false; //跳过数据校验 boolean skipDataVal = false; //跳过数据校验
StringBuffer pkStr = new StringBuffer() , allStr = new StringBuffer(); StringBuffer pkStr = new StringBuffer(), allStr = new StringBuffer();
for(int col=0 ; col<colNum ; col++){ for (int col = 0; col < colNum; col++) {
Cell value = row.getCell(col) ; Cell value = row.getCell(col);
Cell title = titleRow.getCell(col) ; Cell title = titleRow.getCell(col);
String titleValue = getValue(title) ; String titleValue = getValue(title);
TableProperties tableProperties = getTableProperties(event, titleValue); TableProperties tableProperties = getTableProperties(event, titleValue);
if(tableProperties!=null && value!=null){ if (tableProperties != null && value != null) {
String valuestr = getValue(value) ; String valuestr = getValue(value);
if(!StringUtils.isBlank(valuestr)) { if (!StringUtils.isBlank(valuestr)) {
if(tableProperties.isModits()){ if (tableProperties.isModits()) {
if(!StringUtils.isBlank(valuestr)) { if (!StringUtils.isBlank(valuestr)) {
multiValues.put(tableProperties.getFieldname(), valuestr) ; multiValues.put(tableProperties.getFieldname(), valuestr);
} }
}else{ } else {
if(tableProperties.isSeldata()){ if (tableProperties.isSeldata()) {
SysDic sysDic = Dict.getInstance().getDicItem(valuestr) ; SysDic sysDic = Dict.getInstance().getDicItem(valuestr);
if(sysDic!=null){ if (sysDic != null) {
values.put(tableProperties.getFieldname(), sysDic.getName()) ; values.put(tableProperties.getFieldname(), sysDic.getName());
}else{ } else {
List<SysDic> dicItemList = Dict.getInstance().getSysDic(tableProperties.getSeldatacode()); List<SysDic> dicItemList = Dict.getInstance().getSysDic(tableProperties.getSeldatacode());
if(dicItemList!=null && dicItemList.size() > 0) { if (dicItemList != null && dicItemList.size() > 0) {
for(SysDic dicItem : dicItemList) { for (SysDic dicItem : dicItemList) {
if(dicItem.getName().equals(valuestr)) { if (dicItem.getName().equals(valuestr)) {
values.put(tableProperties.getFieldname(), dicItem.isDiscode()?dicItem.getCode():dicItem.getId()) ; break ; values.put(tableProperties.getFieldname(), dicItem.isDiscode() ? dicItem.getCode() : dicItem.getId());
break;
} }
} }
} }
} }
}else if(tableProperties.isReffk() && refValues.get(tableProperties.getFieldname())!=null){ } else if (tableProperties.isReffk() && refValues.get(tableProperties.getFieldname()) != null) {
List keys = refValues.get(tableProperties.getFieldname()) ; List keys = refValues.get(tableProperties.getFieldname());
if(keys != null) { if (keys != null) {
values.put(tableProperties.getFieldname() , getRefid(tableProperties,refValues.get(tableProperties.getFieldname()) , valuestr)) ; values.put(tableProperties.getFieldname(), getRefid(tableProperties, refValues.get(tableProperties.getFieldname()), valuestr));
} }
}else{ } else {
values.put(tableProperties.getFieldname(), valuestr) ; values.put(tableProperties.getFieldname(), valuestr);
} }
if(tableProperties.isPk() && !tableProperties.getFieldname().equalsIgnoreCase("id")){ if (tableProperties.isPk() && !tableProperties.getFieldname().equalsIgnoreCase("id")) {
pkStr.append(valuestr) ; pkStr.append(valuestr);
} }
} }
allStr.append(valuestr) ; allStr.append(valuestr);
} }
event.getDSData().getReport().setBytes(event.getDSData().getReport().getBytes() + valuestr.length()); event.getDSData().getReport().setBytes(event.getDSData().getReport().getBytes() + valuestr.length());
event.getDSData().getReport().getAtompages().incrementAndGet() ; event.getDSData().getReport().getAtompages().incrementAndGet();
} }
} }
values.put("orgi", event.getOrgi()) ; values.put("orgi", event.getOrgi());
if(values.get("id") == null){ if (values.get("id") == null) {
if(pkStr.length() > 0) { if (pkStr.length() > 0) {
values.put("id", MainUtils.md5(pkStr.append(event.getDSData().getTask().getTablename()).toString())) ; values.put("id", MainUtils.md5(pkStr.append(event.getDSData().getTask().getTablename()).toString()));
}else { } else {
values.put("id", MainUtils.md5(allStr.append(event.getDSData().getTask().getTablename()).toString())) ; values.put("id", MainUtils.md5(allStr.append(event.getDSData().getTask().getTablename()).toString()));
} }
} }
if(event.getValues()!=null && event.getValues().size() > 0){ if (event.getValues() != null && event.getValues().size() > 0) {
values.putAll(event.getValues()); values.putAll(event.getValues());
} }
values.putAll(multiValues.asMap()); values.putAll(multiValues.asMap());
String validFaildMessage = null ; String validFaildMessage = null;
for(TableProperties tp : table.getTableproperty()){ for (TableProperties tp : table.getTableproperty()) {
if(!StringUtils.isBlank(tp.getDefaultvaluetitle())) { if (!StringUtils.isBlank(tp.getDefaultvaluetitle())) {
String valuestr = (String) values.get(tp.getFieldname()) ; String valuestr = (String) values.get(tp.getFieldname());
if(tp.getDefaultvaluetitle().indexOf("required") >= 0 && StringUtils.isBlank(valuestr)) { if (tp.getDefaultvaluetitle().indexOf("required") >= 0 && StringUtils.isBlank(valuestr)) {
skipDataVal = true ; validFaildMessage = "required" ;break ; skipDataVal = true;
}else if(valuestr!=null && (tp.getDefaultvaluetitle().indexOf("numstr") >= 0 && !valuestr.matches("[\\d]{1,}"))) { validFaildMessage = "required";
skipDataVal = true ; validFaildMessage = "numstr" ;break ; break;
}else if(valuestr!=null && (tp.getDefaultvaluetitle().indexOf("datenum") >= 0 || tp.getDefaultvaluetitle().indexOf("datetime") >= 0 )) { } else if (valuestr != null && (tp.getDefaultvaluetitle().indexOf("numstr") >= 0 && !valuestr.matches("[\\d]{1,}"))) {
if(!valuestr.matches("[\\d]{4,4}-[\\d]{2,2}-[\\d]{2,2}") && !valuestr.matches("[\\d]{4,4}-[\\d]{2,2}-[\\d]{2} [\\d]{2,2}:[\\d]{2,2}:[\\d]{2,2}")) { skipDataVal = true;
skipDataVal = true ; validFaildMessage = "datenum" ; break ; validFaildMessage = "numstr";
}else { break;
if(valuestr.matches("[\\d]{4,4}-[\\d]{2,2}-{1,1}")) { } else if (valuestr != null && (tp.getDefaultvaluetitle().indexOf("datenum") >= 0 || tp.getDefaultvaluetitle().indexOf("datetime") >= 0)) {
if("date".equals(tp.getDefaultfieldvalue())) { if (!valuestr.matches("[\\d]{4,4}-[\\d]{2,2}-[\\d]{2,2}") && !valuestr.matches("[\\d]{4,4}-[\\d]{2,2}-[\\d]{2} [\\d]{2,2}:[\\d]{2,2}:[\\d]{2,2}")) {
skipDataVal = true;
validFaildMessage = "datenum";
break;
} else {
if (valuestr.matches("[\\d]{4,4}-[\\d]{2,2}-{1,1}")) {
if ("date".equals(tp.getDefaultfieldvalue())) {
values.put(tp.getFieldname(), MainUtils.simpleDateFormat.parse(valuestr)); values.put(tp.getFieldname(), MainUtils.simpleDateFormat.parse(valuestr));
}else { } else {
values.put(tp.getFieldname(), MainUtils.simpleDateFormat.format(MainUtils.simpleDateFormat.parse(valuestr))); values.put(tp.getFieldname(), MainUtils.simpleDateFormat.format(MainUtils.simpleDateFormat.parse(valuestr)));
} }
}else if(valuestr.matches("[\\d]{4,4}-[\\d]{2,2}-[\\d]{2,2} [\\d]{2,2}:[\\d]{2,2}:[\\d]{2,2}")) { } else if (valuestr.matches("[\\d]{4,4}-[\\d]{2,2}-[\\d]{2,2} [\\d]{2,2}:[\\d]{2,2}:[\\d]{2,2}")) {
if("date".equals(tp.getDefaultfieldvalue())) { if ("date".equals(tp.getDefaultfieldvalue())) {
values.put(tp.getFieldname(), MainUtils.dateFormate.parse(valuestr)); values.put(tp.getFieldname(), MainUtils.dateFormate.parse(valuestr));
}else { } else {
values.put(tp.getFieldname(), MainUtils.simpleDateFormat.format(MainUtils.dateFormate.parse(valuestr))); values.put(tp.getFieldname(), MainUtils.simpleDateFormat.format(MainUtils.dateFormate.parse(valuestr)));
} }
@ -209,143 +217,144 @@ public class ExcelImportProecess extends DataProcess{
} }
} }
} }
if(tp.isReffk() && !StringUtils.isBlank(tp.getReftbid()) && refValues.get(tp.getFieldname()) == null){ if (tp.isReffk() && !StringUtils.isBlank(tp.getReftbid()) && refValues.get(tp.getFieldname()) == null) {
DataExchangeInterface exchange = (DataExchangeInterface) MainContext.getContext().getBean(tp.getReftbid()) ; DataExchangeInterface exchange = (DataExchangeInterface) MainContext.getContext().getBean(tp.getReftbid());
exchange.process(data, event.getOrgi()); exchange.process(data, event.getOrgi());
} }
} }
if(!values.containsKey("orgi")) { if (!values.containsKey("orgi")) {
skipDataVal = true ; skipDataVal = true;
} }
event.getDSData().getReport().setTotal(pages.intValue()); event.getDSData().getReport().setTotal(pages.intValue());
values.put("creater", event.getValues().get("creater")) ; values.put("creater", event.getValues().get("creater"));
if(data!=null && skipDataVal == false) { if (data != null && skipDataVal == false) {
MainUtils.populate(data, values); MainUtils.populate(data, values);
pages.incrementAndGet() ; pages.incrementAndGet();
event.getDSData().getProcess().process(data); event.getDSData().getProcess().process(data);
}else if(data == null){ } else if (data == null) {
/** /**
* 导入的数据只写入ES * 导入的数据只写入ES
*/ */
if(skipDataVal == true) { //跳过 if (skipDataVal == true) { //跳过
values.put("status", "invalid") ; values.put("status", "invalid");
values.put("validresult", "invalid") ; values.put("validresult", "invalid");
values.put("validmessage", validFaildMessage!=null ? validFaildMessage : "") ; values.put("validmessage", validFaildMessage != null ? validFaildMessage : "");
}else { } else {
values.put("validresult", "valid") ; values.put("validresult", "valid");
} }
values.put("status", MainContext.NamesDisStatusType.NOT.toString()) ; values.put("status", MainContext.NamesDisStatusType.NOT.toString());
values.put("batid", event.getBatid()) ; values.put("batid", event.getBatid());
values.put("createtime", System.currentTimeMillis()) ; values.put("createtime", System.currentTimeMillis());
values.put("callstatus", MainContext.NameStatusType.NOTCALL.toString()) ; values.put("callstatus", MainContext.NameStatusType.NOTCALL.toString());
values.put("execid", event.getDSData().getReport().getId()) ; values.put("execid", event.getDSData().getReport().getId());
if(i%500 == 0) { if (i % 500 == 0) {
MainContext.getContext().getBean(ReporterRepository.class).save(event.getDSData().getReport()) ; MainContext.getContext().getBean(ReporterRepository.class).save(event.getDSData().getReport());
} }
if(values.get("cusid")==null) { if (values.get("cusid") == null) {
/** /**
* *
*/ */
values.put("cusid", values.get("id")) ; values.put("cusid", values.get("id"));
} }
pages.incrementAndGet() ; pages.incrementAndGet();
event.getDSData().getProcess().process(values); event.getDSData().getProcess().process(values);
/** /**
* 访客信息表 * 访客信息表
*/ */
} }
if(skipDataVal == true) { //跳过 if (skipDataVal == true) { //跳过
errors.incrementAndGet(); errors.incrementAndGet();
continue ; continue;
} }
} }
} }
event.setTimes(System.currentTimeMillis() - start); event.setTimes(System.currentTimeMillis() - start);
event.getDSData().getReport().setEndtime(new Date()); event.getDSData().getReport().setEndtime(new Date());
event.getDSData().getReport().setAmount(String.valueOf((float)event.getTimes()/1000f)); event.getDSData().getReport().setAmount(String.valueOf((float) event.getTimes() / 1000f));
event.getDSData().getReport().setStatus(MainContext.TaskStatusType.END.getType()); event.getDSData().getReport().setStatus(MainContext.TaskStatusType.END.getType());
event.getDSData().getReport().setTotal(pages.intValue()); event.getDSData().getReport().setTotal(pages.intValue());
event.getDSData().getReport().setPages(pages.intValue()); event.getDSData().getReport().setPages(pages.intValue());
event.getDSData().getReport().setErrors(errors.intValue()); event.getDSData().getReport().setErrors(errors.intValue());
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); e.printStackTrace();
}finally{ } finally {
if(is!=null){ if (is != null) {
try { try {
is.close(); is.close();
} catch (IOException e) { } catch (IOException e) {
e.printStackTrace(); e.printStackTrace();
} }
} }
if(event.getDSData().getFile().exists()){ if (event.getDSData().getFile().exists()) {
event.getDSData().getFile().delete() ; event.getDSData().getFile().delete();
} }
/** /**
* 更新数据 * 更新数据
*/ */
MainContext.getContext().getBean(ReporterRepository.class).save(event.getDSData().getReport()) ; MainContext.getContext().getBean(ReporterRepository.class).save(event.getDSData().getReport());
if(event.getDSData().getClazz() == null && !StringUtils.isBlank(event.getBatid())) { if (event.getDSData().getClazz() == null && !StringUtils.isBlank(event.getBatid())) {
JobDetailRepository batchRes = MainContext.getContext().getBean(JobDetailRepository.class) ; JobDetailRepository batchRes = MainContext.getContext().getBean(JobDetailRepository.class);
JobDetail batch = this.event.getDSData().getJobDetail(); JobDetail batch = this.event.getDSData().getJobDetail();
if(batch == null) { if (batch == null) {
batch = batchRes.findByIdAndOrgi(event.getBatid(), event.getOrgi()) ; batch = batchRes.findByIdAndOrgi(event.getBatid(), event.getOrgi());
} }
if(batch!=null) { if (batch != null) {
batch.setNamenum(batch.getNamenum() + pages.intValue()); batch.setNamenum(batch.getNamenum() + pages.intValue());
batch.setValidnum(batch.getValidnum() + (pages.intValue() - errors.intValue())); batch.setValidnum(batch.getValidnum() + (pages.intValue() - errors.intValue()));
batch.setInvalidnum(batch.getInvalidnum() + errors.intValue()); batch.setInvalidnum(batch.getInvalidnum() + errors.intValue());
batch.setExecnum(batch.getExecnum() + 1); batch.setExecnum(batch.getExecnum() + 1);
batch.setNotassigned(batch.getNotassigned() + (pages.intValue() - errors.intValue())); batch.setNotassigned(batch.getNotassigned() + (pages.intValue() - errors.intValue()));
batchRes.save(batch) ; batchRes.save(batch);
} }
} }
event.getDSData().getProcess().end(); event.getDSData().getProcess().end();
} }
} }
private String getRefid(TableProperties tp , List<Object> dataList , String value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{ private String getRefid(TableProperties tp, List<Object> dataList, String value) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {
String id = "" ; String id = "";
for(Object data : dataList){ for (Object data : dataList) {
Object target = null ; Object target = null;
if(PropertyUtils.isReadable(data, "name")){ if (PropertyUtils.isReadable(data, "name")) {
target = BeanUtils.getProperty(data, "name") ; target = BeanUtils.getProperty(data, "name");
if(target!=null && target.equals(value)){ if (target != null && target.equals(value)) {
id = BeanUtils.getProperty(data, "id") ; id = BeanUtils.getProperty(data, "id");
} }
} }
if(PropertyUtils.isReadable(data, "tag")){ if (PropertyUtils.isReadable(data, "tag")) {
target = BeanUtils.getProperty(data, "tag") ; target = BeanUtils.getProperty(data, "tag");
if(target!=null && target.equals(value)){ if (target != null && target.equals(value)) {
id = BeanUtils.getProperty(data, "id") ; id = BeanUtils.getProperty(data, "id");
} }
} }
if(StringUtils.isBlank(id) && PropertyUtils.isReadable(data, "title")){ if (StringUtils.isBlank(id) && PropertyUtils.isReadable(data, "title")) {
target = BeanUtils.getProperty(data, "title") ; target = BeanUtils.getProperty(data, "title");
if(target!=null && target.equals(value)){ if (target != null && target.equals(value)) {
id = BeanUtils.getProperty(data, "id") ; id = BeanUtils.getProperty(data, "id");
} }
} }
if(StringUtils.isBlank(id)){ if (StringUtils.isBlank(id)) {
target = BeanUtils.getProperty(data, "id") ; target = BeanUtils.getProperty(data, "id");
if(target!=null && target.equals(value)){ if (target != null && target.equals(value)) {
id = target.toString() ; id = target.toString();
} }
} }
} }
return id ; return id;
} }
private TableProperties getTableProperties(DSDataEvent event , String title){ private TableProperties getTableProperties(DSDataEvent event, String title) {
TableProperties tableProperties = null ; TableProperties tableProperties = null;
for(TableProperties tp : event.getDSData().getTask().getTableproperty()){ for (TableProperties tp : event.getDSData().getTask().getTableproperty()) {
if(tp.getName().equals(title) || tp.getFieldname().equals(title)){ if (tp.getName().equals(title) || tp.getFieldname().equals(title)) {
tableProperties = tp ; break ; tableProperties = tp;
break;
} }
} }
return tableProperties; return tableProperties;
@ -354,11 +363,12 @@ public class ExcelImportProecess extends DataProcess{
private boolean isExcel2007(String fileName) { private boolean isExcel2007(String fileName) {
return fileName.matches("^.+\\.(?i)(xlsx)$"); return fileName.matches("^.+\\.(?i)(xlsx)$");
} }
@SuppressWarnings("deprecation") @SuppressWarnings("deprecation")
private String getValue(Cell cell){ private String getValue(Cell cell) {
String strCell = ""; String strCell = "";
if(cell!=null){ if (cell != null) {
short dt = cell.getCellStyle().getDataFormat() ; short dt = cell.getCellStyle().getDataFormat();
switch (cell.getCellType()) { switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING: case HSSFCell.CELL_TYPE_STRING:
strCell = cell.getStringCellValue(); strCell = cell.getStringCellValue();
@ -383,7 +393,7 @@ public class ExcelImportProecess extends DataProcess{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
double value = cell.getNumericCellValue(); double value = cell.getNumericCellValue();
strCell = sdf.format(org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value)); strCell = sdf.format(org.apache.poi.ss.usermodel.DateUtil.getJavaDate(value));
}else{ } else {
if (HSSFDateUtil.isCellDateFormatted(cell)) { if (HSSFDateUtil.isCellDateFormatted(cell)) {
SimpleDateFormat sdf = null; SimpleDateFormat sdf = null;
@ -393,31 +403,31 @@ public class ExcelImportProecess extends DataProcess{
sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
} }
strCell = sdf.format(cell.getDateCellValue()); strCell = sdf.format(cell.getDateCellValue());
}else{ } else {
boolean isNumber = isNumberFormat(dt) ; boolean isNumber = isNumberFormat(dt);
if(isNumber){ if (isNumber) {
DecimalFormat numberFormat = getNumberFormat(cell.getCellStyle().getDataFormatString()) ; DecimalFormat numberFormat = getNumberFormat(cell.getCellStyle().getDataFormatString());
if(numberFormat!=null){ if (numberFormat != null) {
strCell = String.valueOf(numberFormat.format(cell.getNumericCellValue())); strCell = String.valueOf(numberFormat.format(cell.getNumericCellValue()));
}else{ } else {
strCell = String.valueOf(cell.getNumericCellValue()); strCell = String.valueOf(cell.getNumericCellValue());
} }
}else{ } else {
strCell = String.valueOf(format.format(cell.getNumericCellValue())) ; strCell = String.valueOf(format.format(cell.getNumericCellValue()));
} }
} }
} }
break; break;
case HSSFCell.CELL_TYPE_FORMULA: { case HSSFCell.CELL_TYPE_FORMULA: {
// 判断当前的cell是否为Date // 判断当前的cell是否为Date
boolean isNumber = isNumberFormat(dt) ; boolean isNumber = isNumberFormat(dt);
try{ try {
if(isNumber){ if (isNumber) {
strCell = String.valueOf(cell.getNumericCellValue()); strCell = String.valueOf(cell.getNumericCellValue());
}else{ } else {
strCell = ""; strCell = "";
} }
}catch(Exception ex){ } catch (Exception ex) {
ex.printStackTrace(); ex.printStackTrace();
strCell = cell.getRichStringCellValue().getString(); strCell = cell.getRichStringCellValue().getString();
} }
@ -434,11 +444,11 @@ public class ExcelImportProecess extends DataProcess{
return strCell; return strCell;
} }
@SuppressWarnings({ "deprecation", "unused" }) @SuppressWarnings({"deprecation", "unused"})
private String getDataType(Cell cell){ private String getDataType(Cell cell) {
String dataType = "string"; String dataType = "string";
if(cell!=null){ if (cell != null) {
short dt = cell.getCellStyle().getDataFormat() ; short dt = cell.getCellStyle().getDataFormat();
switch (cell.getCellType()) { switch (cell.getCellType()) {
case HSSFCell.CELL_TYPE_STRING: case HSSFCell.CELL_TYPE_STRING:
dataType = "string"; dataType = "string";
@ -449,18 +459,18 @@ public class ExcelImportProecess extends DataProcess{
case HSSFCell.CELL_TYPE_BLANK: case HSSFCell.CELL_TYPE_BLANK:
if (HSSFDateUtil.isCellDateFormatted(cell)) { if (HSSFDateUtil.isCellDateFormatted(cell)) {
if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) { if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
dataType = "datetime" ; dataType = "datetime";
} else {// 日期 } else {// 日期
dataType = "datetime" ; dataType = "datetime";
} }
} else if (cell.getCellStyle().getDataFormat() == 58){ } else if (cell.getCellStyle().getDataFormat() == 58) {
dataType = "datetime" ; dataType = "datetime";
}else{ } else {
boolean isNumber = isNumberFormat(dt) ; boolean isNumber = isNumberFormat(dt);
if(isNumber){ if (isNumber) {
dataType = "number"; dataType = "number";
}else{ } else {
dataType = "string"; dataType = "string";
} }
} }
@ -468,25 +478,25 @@ public class ExcelImportProecess extends DataProcess{
case HSSFCell.CELL_TYPE_NUMERIC: case HSSFCell.CELL_TYPE_NUMERIC:
if (HSSFDateUtil.isCellDateFormatted(cell)) { if (HSSFDateUtil.isCellDateFormatted(cell)) {
if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) { if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
dataType = "datetime" ; dataType = "datetime";
} else {// 日期 } else {// 日期
dataType = "datetime" ; dataType = "datetime";
} }
} else if (cell.getCellStyle().getDataFormat() == 58){ } else if (cell.getCellStyle().getDataFormat() == 58) {
dataType = "datetime" ; dataType = "datetime";
}else{ } else {
if (HSSFDateUtil.isCellDateFormatted(cell)) { if (HSSFDateUtil.isCellDateFormatted(cell)) {
if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) { if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) {
dataType = "datetime" ; dataType = "datetime";
} else {// 日期 } else {// 日期
dataType = "datetime" ; dataType = "datetime";
} }
}else{ } else {
boolean isNumber = isNumberFormat(dt) ; boolean isNumber = isNumberFormat(dt);
if(isNumber){ if (isNumber) {
dataType = "number"; dataType = "number";
}else{ } else {
dataType = "string"; dataType = "string";
} }
} }
@ -494,10 +504,10 @@ public class ExcelImportProecess extends DataProcess{
break; break;
case HSSFCell.CELL_TYPE_FORMULA: { case HSSFCell.CELL_TYPE_FORMULA: {
// 判断当前的cell是否为Date // 判断当前的cell是否为Date
boolean isNumber = isNumberFormat(dt) ; boolean isNumber = isNumberFormat(dt);
if(isNumber){ if (isNumber) {
dataType = "number"; dataType = "number";
}else{ } else {
dataType = "string"; dataType = "string";
} }
break; break;
@ -511,50 +521,100 @@ public class ExcelImportProecess extends DataProcess{
return dataType; return dataType;
} }
private DecimalFormat getNumberFormat(String dataformat){ private DecimalFormat getNumberFormat(String dataformat) {
DecimalFormat numberFormat = null ; DecimalFormat numberFormat = null;
int index = dataformat.indexOf("_") > 0 ? dataformat.indexOf("_") : dataformat.indexOf(";") ; int index = dataformat.indexOf("_") > 0 ? dataformat.indexOf("_") : dataformat.indexOf(";");
if(index > 0){ if (index > 0) {
String format = dataformat.substring( 0 , index) ; String format = dataformat.substring(0, index);
if(format.matches("[\\d.]{1,}")){ if (format.matches("[\\d.]{1,}")) {
numberFormat = new DecimalFormat(format); numberFormat = new DecimalFormat(format);
} }
} }
return numberFormat ; return numberFormat;
} }
private boolean isNumberFormat(short dataType){ private boolean isNumberFormat(short dataType) {
boolean number = false ; boolean number = false;
switch(dataType){ switch (dataType) {
case 180 : number = true ; break; case 180:
case 181 : number = true ; break; number = true;
case 182 : number = true ; break; break;
case 178 : number = true ; break; case 181:
case 177 : number = true ; break; number = true;
case 176 : number = true ; break; break;
case 183 : number = true ; break; case 182:
case 185 : number = true ; break; number = true;
case 186 : number = true ; break; break;
case 179 : number = true ; break; case 178:
case 187 : number = true ; break; number = true;
case 7 : number = true ; break; break;
case 8 : number = true ; break; case 177:
case 44 : number = true ; break; number = true;
case 10 : number = true ; break; break;
case 12 : number = true ; break; case 176:
case 13 : number = true ; break; number = true;
case 188 : number = true ; break; break;
case 189 : number = true ; break; case 183:
case 190 : number = true ; break; number = true;
case 191 : number = true ; break; break;
case 192 : number = true ; break; case 185:
case 193 : number = true ; break; number = true;
case 194 : number = true ; break; break;
case 11 : number = true ; break; case 186:
number = true;
break;
case 179:
number = true;
break;
case 187:
number = true;
break;
case 7:
number = true;
break;
case 8:
number = true;
break;
case 44:
number = true;
break;
case 10:
number = true;
break;
case 12:
number = true;
break;
case 13:
number = true;
break;
case 188:
number = true;
break;
case 189:
number = true;
break;
case 190:
number = true;
break;
case 191:
number = true;
break;
case 192:
number = true;
break;
case 193:
number = true;
break;
case 194:
number = true;
break;
case 11:
number = true;
break;
} }
return number ; return number;
} }