12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082 |
- /**
- *
- * Copyright (c) behosoft Co.,Ltd.
- * All Rights Reserved.
- *
- * This software is the confidential and proprietary information of behosoft.
- * (Social Security Department). You shall not disclose such
- * Confidential Information and shall use it only in accordance with
- * the terms of the license agreement you entered into with behosoft.
- *
- * Distributable under GNU LGPL license by gnu.org
- */
- package com.behosoft.util;
- import java.beans.PropertyDescriptor;
- import java.io.File;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.io.InputStream;
- import java.math.BigDecimal;
- import java.math.BigInteger;
- import java.sql.Blob;
- import java.sql.ResultSet;
- import java.sql.ResultSetMetaData;
- import java.sql.SQLException;
- import java.sql.Timestamp;
- import java.text.SimpleDateFormat;
- import java.util.ArrayList;
- import java.util.Calendar;
- import java.util.Collection;
- import java.util.Date;
- import java.util.HashMap;
- import java.util.List;
- import java.util.Map;
- import java.util.regex.Pattern;
- import javax.persistence.Column;
- import javax.servlet.http.HttpServletRequest;
- import net.sf.json.JSONNull;
- import org.apache.commons.beanutils.PropertyUtils;
- import org.apache.commons.logging.Log;
- import org.apache.commons.logging.LogFactory;
- import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
- import org.hibernate.mapping.Property;
- import org.josql.Query;
- import org.josql.QueryExecutionException;
- import org.josql.QueryParseException;
- import org.josql.QueryResults;
- import org.springframework.util.CollectionUtils;
- import com.behosoft.edi.context.EdiBusinessSessionContext;
- import com.behosoft.edi.model.vo.EdiUserVO;
- import com.behosoft.framework.web.dto.UploadFileDto;
- import com.behosoft.framework.web.exception.CommonException;
- import com.behosoft.framework.web.model.RecordBO;
- import com.behosoft.lis.BusinessConstants;
- import com.behosoft.lis.util.PDAContextUtil;
- import com.behosoft.util.ftputil.FTPUtil;
- import com.wondersgroup.framework.core.bo.Page;
- import com.wondersgroup.framework.core.web.vo.JsonDateValueProcessor;
- import com.wondersgroup.framework.util.preloadutil.AppContextUtils;
- import com.wondersgroup.saas.exception.UtilsException;
- import com.wondersgroup.saas.meta.query.ConditionRule;
- import com.wondersgroup.saas.meta.query.QueryBean;
- import com.wondersgroup.saas.sql.HibernateMetaSupport;
- import com.wondersgroup.saas.util.CommonUtils;
- import com.wondersgroup.saas.util.FileExposeUtil;
- import com.wondersgroup.saas.util.PropertiesManager;
- import dateparse.Expression;
- import dateparse.util.StringUtils;
- /**
- * <p>
- * Title: WMS_common_utils
- * </p>
- * <p>
- * Description: 公共工具类
- * </p>
- *
- * @author liudd
- * @version $Revision$ 2009-8-12
- * @author (lastest modification by $Author$)
- * @since 1.0
- */
- @SuppressWarnings("unchecked")
- public class EdiBusinessUtils extends CommonUtils {
- /**
- * LOGGER
- */
- private static final Log LOGGER = LogFactory.getLog(EdiBusinessUtils.class);
- /**
- * <p>
- * Description: 附加创建或更新信息
- * </p>
- *
- * @param bo BO对象
- */
- public static void appendRecordForBO(RecordBO bo) {
- String loginName = "system";
- Map<String,Object> params = PDAContextUtil.getParams();
-
- if (null != params)
- {
- Object userObject = params.get(BusinessConstants.USER_INFO);
-
- if (null != userObject)
- {
- EdiUserVO userVO = (EdiUserVO)userObject;
-
- loginName = userVO.getUserLoginName();
- }
- }
-
- if( EdiBusinessSessionContext.getLoginName()!=null){
- loginName = String.valueOf(EdiBusinessSessionContext.getLoginName());
- }
- appendRecordForBO(bo, loginName, BusinessConstants.PROCESS_MODE_WEB);
- }
- /**
- * <p>
- * Description: 清除创建或更新信息
- * </p>
- *
- * @param bo BO对象
- */
- public static void clearRecordForBO(RecordBO bo) {
- bo.setCreationMethod(null);
- bo.setCreationTime(null);
- bo.setCreatedBy(null);
- bo.setUpdatedBy(null);
- bo.setUpdateMethod(null);
- bo.setUpdateTime(null);
- }
- /**
- * <p>
- * Description:append some data for bo
- * </p>
- *
- * @param bo RecordBO
- * @param loginName loginName
- */
- public static void appendRecordForBO(RecordBO bo, String loginName) {
- appendRecordForBO(bo, loginName, BusinessConstants.PROCESS_MODE_WEB);
- }
- /**
- * <p>
- * Description:append some data for bo
- * </p>
- *
- * @param bo RecordBO
- * @param loginName 操作人
- * @param processMethod 处理方法
- */
- public static void appendRecordForBO(RecordBO bo, String loginName, String processMethod) {
- Date date = new Date();
- if (bo.getCreationTime() == null) {
- bo.setCreationTime(date);
- bo.setUpdateTime(date);
- }
- else {
- bo.setUpdateTime(date);
- }
- if (bo.getCreatedBy() == null) {
- bo.setCreatedBy(loginName);
- bo.setUpdatedBy(loginName);
- bo.setCreationMethod(processMethod);
- bo.setUpdateMethod(processMethod);
- }
- else {
- bo.setUpdatedBy(loginName);
- bo.setUpdateMethod(processMethod);
- }
- if (bo.getDeleteFlag() == null) {
- bo.setDeleteFlag(0);
- }
- }
- /**
- * <p>
- * Description: append some data for map
- * </p>
- *
- * @param map
- */
- public static void appendRecordForMap(Map<String, Object> map) {
- map.put("updatedBy", EdiBusinessSessionContext.getLoginName());
- map.put("updateTime", new Date());
- map.put("updateMethod", BusinessConstants.PROCESS_MODE_WEB);
- }
- /**
- * <p>
- * Description: append some data for map
- * </p>
- *
- * @param map
- * @param processMode 处理方式(web、edi、ws)
- */
- public static void appendRecordForMap(Map<String, Object> map, String processMode) {
- if (processMode == null || processMode.length() == 0) {
- appendRecordForMap(map);
- }
- else {
- map.put("updatedBy", EdiBusinessSessionContext.getLoginName());
- map.put("updateTime", new Date());
- map.put("updateMethod", BusinessConstants.PROCESS_MODE_WEB);
- }
- }
- /**
- * <p>
- * Description: append some data for map
- * </p>
- *
- * @param map
- * @param processMode 处理方式(web、edi、ws)
- */
- public static void appendRecordForMap(Map<String, Object> map, String processMode, String processor) {
- if (processMode == null || processMode.length() == 0) {
- processMode = BusinessConstants.PROCESS_MODE_WEB;
- }
- if (processor == null || processor.length() == 0) {
- processor = EdiBusinessSessionContext.getLoginName();
- }
- map.put("updatedBy", processor);
- map.put("updateTime", new Date());
- map.put("updateMethod", processMode);
- }
- public static List<String> spilitArrayFromString(String str, String spliter) {
- List<String> list = new ArrayList<String>();
- if (isNotBlank(str)) {
- String[] spliteArray = str.split(spliter);
- for (String s : spliteArray) {
- if (isNotBlank(s)) {
- list.add(s.trim());
- }
- }
- }
- return list;
- }
- /**
- * <p>
- * Description:检查字符串不为NULL,也不为空字符串
- * </p>
- *
- * @param value
- * @return
- */
- public static boolean isNotBlank(Object value) {
- return !JSONNull.getInstance().equals(value)
- && !(value instanceof String && ((String) value).trim().equals(""));
- }
- public static <T> T mapRowDataToPojo(Class<T> pojo, Class<?> boClass, ResultSet rs,
- HibernateMetaSupport hibernateMetaSupport) throws SQLException {
- return mapRowDataToPojo(pojo, boClass, rs, hibernateMetaSupport, new HashMap<String, String>());
- }
- /**
- * <p>
- * Description: 将数据集中的行映射为POJO对象
- * </p>
- *
- * @param <T>
- * @param pojo
- * @param rs
- * @param hibernateMetaSupport
- * @return
- * @throws InstantiationException
- * @throws IllegalAccessException
- * @throws SQLException
- */
- public static <T> T mapRowDataToPojo(Class<T> pojo, Class<?> boClass, ResultSet rs,
- HibernateMetaSupport hibernateMetaSupport, Map<String, String> dateMap) throws SQLException {
- // if (dateFormat != null) {
- // jsonDateValueProcessor.setDateFormat(new
- // SimpleDateFormat(dateFormat));
- // }
- if (hibernateMetaSupport == null) {
- hibernateMetaSupport =
- (HibernateMetaSupport) AppContextUtils.getApplicationContext().getBean("hibernateMetaSupport");
- }
- T instance = null;
- try {
- instance = pojo.newInstance();
- }
- catch (Exception e) {
- throw new UtilsException(e.getMessage());
- }
- ResultSetMetaData resultSetMetaData = rs.getMetaData();
- for (int i = 1; i <= resultSetMetaData.getColumnCount(); i++) {
- String fieldName = resultSetMetaData.getColumnName(i);
- try {
- Property property = hibernateMetaSupport.getPropertyByColumnName(boClass, fieldName, false);
- if (property == null) {
- LOGGER.info("No Such Field: " + fieldName + " For " + pojo.getName());
- continue;
- }
- fieldName = property.getName();
- Object value = rs.getObject(i);
- if (property.getType().getReturnedClass() == Boolean.class
- || property.getType().getReturnedClass() == boolean.class) {
- value = rs.getBoolean(i);
- }
- if (value != null && value instanceof BigDecimal) {
- PropertyUtils.setProperty(instance, fieldName, ((BigDecimal) value).doubleValue());
- }
- else if (value != null && value instanceof BigInteger) {
- PropertyUtils.setProperty(instance, fieldName, ((BigInteger) value).longValue());
- }
- else if (value != null && property.getType().getReturnedClass().equals(Short.class)) {
- PropertyUtils.setProperty(instance, fieldName, ((Integer) value).shortValue());
- }
- else if (value != null && value instanceof Date) {
- if (dateMap != null) {
- for (Map.Entry<String, String> entry : dateMap.entrySet()) {
- if (fieldName.equals(entry.getKey())) {
- JsonDateValueProcessor jsonDateValueProcessor = new JsonDateValueProcessor();
- if (entry.getValue() != null || !"".equals(entry.getValue())) {
- jsonDateValueProcessor.setDateFormat(new SimpleDateFormat(entry.getValue()));
- }
- value = jsonDateValueProcessor.processArrayValue((value), null);
- break;
- }
- }
- }
- PropertyUtils.setProperty(instance, fieldName, value);
- }
- else if (value != null
- && (value instanceof byte[] || value instanceof InputStream || value instanceof Blob)) {
- value = rs.getBlob(i);
- PropertyUtils.setProperty(instance, fieldName, value);
- }
- else {
- PropertyUtils.setProperty(instance, fieldName, value);
- }
- }
- catch (NoSuchMethodException e) {
- LOGGER.debug("No Such Field: " + fieldName + " For " + pojo.getName());
- }
- catch (Exception e) {
- throw new CommonException("set property value error : " + fieldName + " in class " + pojo.getName(), e);
- }
- }
- return instance;
- }
- /**
- * <p>
- * Description:文件上传
- * </p>
- *
- * @param request
- * @param requestFile request对象中file的name
- * @param rootPath the root path to save
- * @param uniqueKey
- * @param moduleKey
- * @throws Exception
- */
- public static UploadFileDto fileUpload(HttpServletRequest request, String requestFile, String rootPath,
- String moduleKey) {
- MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;
- String[] filenames = multiWrapper.getFileNames(requestFile);
- String[] localPaths = multiWrapper.getFileNames(requestFile);
- if (multiWrapper.hasErrors()) {
- throw new CommonException("io.fileuploaderror");
- }
- if (filenames == null) {
- return null;
- }
- if (filenames.length == 0) {
- throw new CommonException("io.unsupportmethod");
- }
- File[] files = multiWrapper.getFiles(requestFile);
- String path = rootPath + "\\" + moduleKey + "\\";
- String[] filePaths = new String[files.length];
- String[] serverNames = new String[files.length];
- if (!FileExposeUtil.checkFileExist(path)) {
- // create folder
- FileExposeUtil.createFile(path);
- }
- for (int i = 0; i < files.length; i++) {
- try {
- serverNames[i] = System.currentTimeMillis() + filenames[i];
- filePaths[i] = path + serverNames[i];
- // 如果上传文件大小为0,则新建文件
- if (!files[i].exists()) {
- files[i] = File.createTempFile(files[i].getName(), "", files[i].getParentFile());
- }
- FileExposeUtil.copyFile(files[i], filePaths[i]);
- }
- catch (Exception e) {
- throw new CommonException("io.unsupportmethod");
- }
- }
- UploadFileDto dto = new UploadFileDto(localPaths, filePaths, filenames, serverNames);
- return dto;
- }
- /**
- * <p>
- * Description:文件上传
- * </p>
- *
- * @param inputStream 输入流
- * @param fileName 文件名称
- * @param rootPath the root path to save
- * @param moduleKey 子目录名称
- * @throws Exception
- */
- public static String fileUpload(InputStream inputStream, String fileName, String rootPath, String moduleKey) {
- if (fileName == null) {
- throw new CommonException("io.unsupportmethod");
- }
- String path = rootPath + "\\" + moduleKey + "\\";
- if (!FileExposeUtil.checkFileExist(path)) {
- // create folder
- FileExposeUtil.createFile(path);
- }
- SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-ms");
- String serverName = formatter.format(new Date()) + "-" + fileName;
- try {
- FileExposeUtil.saveFile(inputStream, path, serverName, true);
- }
- catch (Exception e) {
- throw new CommonException("io.unsupportmethod");
- }
- return path + "\\" + serverName;
- }
- /**
- * <p>
- * Description:文件上传
- * </p>
- *
- * @param request
- * @param requestFile request对象中file的name
- * @param moduleKey 子目录
- * @throws Exception
- */
- public static UploadFileDto fileUploadForFTP(HttpServletRequest request, String requestFile, String moduleKey) {
- MultiPartRequestWrapper multiWrapper = (MultiPartRequestWrapper) request;
- String[] filenames = multiWrapper.getFileNames(requestFile);
- String[] localPaths = multiWrapper.getFileNames(requestFile);
- if (multiWrapper.hasErrors()) {
- throw new CommonException("io.fileuploaderror");
- }
- if (filenames == null) {
- return null;
- }
- if (filenames.length == 0) {
- throw new CommonException("io.unsupportmethod");
- }
- if (moduleKey == null || org.apache.commons.lang.StringUtils.isWhitespace(moduleKey)) {
- moduleKey = "default";
- }
- else {
- moduleKey = moduleKey.trim();
- }
- File[] files = multiWrapper.getFiles(requestFile);
- String[] localFileNameArrs = new String[files.length];
- String[] filePaths = new String[files.length];
- String[] serverNames = new String[files.length];
- String path = "\\" + moduleKey + "\\";
- for (int i = 0; i < files.length; i++) {
- SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-ms");
- String localFileName = formatter.format(new Date()) + "-" + filenames[i];
- Integer stamp = 0;
- while (FTPUtil.fileExist(localFileName)) {
- stamp += 1;
- localFileName =
- formatter.format(new Date()) + stamp.toString() + "-"
- + FileExposeUtil.getFileName(localFileName);
- }
- serverNames[i] = localFileName;
- filePaths[i] = path.replaceAll("\\\\", "/") + localFileName;
- InputStream is = null;
- try {
- // FileExposeUtil.copyFile(documentSourceAddress,
- // documentTargetAddress);
- is = new FileInputStream(files[i]);
- FTPUtil.uploadFile(is, path, localFileName);
- localFileNameArrs[i] = localFileName;
- }
- catch (Exception e) {
- e.printStackTrace();
- FTPUtil.dirFile(localFileName);
- return null;
- }
- finally {
- try {
- if (is != null) {
- is.close();
- }
- }
- catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- UploadFileDto dto = new UploadFileDto(localPaths, filePaths, filenames, serverNames);
- return dto;
- }
- /**
- * <p>
- * Description:文件上传
- * </p>
- *
- * @param request
- * @param requestFile request对象中file的name
- * @throws Exception
- */
- public static UploadFileDto fileUploadForFTP(HttpServletRequest request, String requestFile) {
- return fileUploadForFTP(request, requestFile, null);
- }
- /**
- * <p>
- * Description:内存查询
- * </p>
- *
- * @param <T> 实体泛型
- * @param entity 实体类型
- * @param datas 数据集
- * @param sql SQL语句,面向实体类型
- * @param params 参数
- * @return
- */
- public static <T> Collection<T> findBySQL(Class<T> entity, Collection<T> datas, String sql, Object... params) {
- if (CollectionUtils.isEmpty(datas)) {
- return null;
- }
- sql = sql.replaceAll("#entity", entity.getName());
- Query query = new Query();
- try {
- query.parse(sql);
- }
- catch (QueryParseException e) {
- throw new UtilsException("parse sql error", e);
- }
- if (params != null) {
- for (int i = 0; i < params.length; i++) {
- query.setVariable(i + 1, params[i]);
- }
- }
- QueryResults qr = null;
- try {
- qr = query.execute(datas);
- }
- catch (QueryExecutionException e) {
- throw new UtilsException("mem query error", e);
- }
- Collection<T> tempColl = qr.getResults();
- if (tempColl == null) {
- tempColl = new ArrayList<T>();
- }
- return tempColl;
- }
- /**
- * <p>
- * Description:内存分页查询
- * </p>
- *
- * @param <T> 实体泛型
- * @param entity 实体类型
- * @param datas 数据集
- * @param sql SQL语句,面向实体类型
- * @param pageNo 页号
- * @param pageSize 页面容量
- * @param params 参数
- * @return
- */
- public static <T> Page findForMapBySQLWithPage(Class<T> entity, Collection<T> datas, String sql, int pageNo,
- int pageSize, Map<String, Object> params) {
- if (CollectionUtils.isEmpty(datas)) {
- return null;
- }
- int start = Page.getStartOfAnyPage(pageNo);
- sql = sql.replaceAll("#entity", entity.getName());
- sql = new StringBuffer(sql).append(" limit ").append(start).append(", ").append(pageSize).toString();
- Query query = new Query();
- try {
- query.parse(sql);
- }
- catch (QueryParseException e) {
- throw new UtilsException("parse sql error", e);
- }
- if (params != null) {
- for (Map.Entry<String, Object> entry : params.entrySet()) {
- query.setVariable(entry.getKey(), entry.getValue());
- }
- }
- QueryResults qr = null;
- try {
- qr = query.execute(datas);
- }
- catch (QueryExecutionException e) {
- throw new UtilsException("mem query error", e);
- }
- List<?> result = qr.getResults();
- Page page = null;
- if (result != null) {
- page = new Page(start, result.size(), datas.size(), pageSize, result);
- }
- else {
- page = new Page(0, 0, 0, pageSize, null);
- }
- return page;
- }
- /**
- * <p>
- * Description:[通过文件名称获取文件类型]
- * </p>
- *
- * @param fileName 文件名称
- * @return
- */
- public static String getFileType(String fileName) {
- String suffix = fileName.substring(fileName.lastIndexOf(".") + 1);
- if (suffix.equals("xls") || suffix.equals("xlsx")) {
- return "excel";
- }
- else if (suffix.equals("doc") || suffix.equals("docx")) {
- return "word";
- }
- return null;
- }
- /**
- * <p>
- * Description:产生具有前缀和后缀的唯一字符串,中间14位
- * </p>
- *
- * @param prefix
- * @param suffix
- * @return
- */
- public static String createUniqueKey(String prefix, String suffix) {
- int randomNumber = (int) (Math.random() * 9);
- Calendar cal = Calendar.getInstance();
- StringBuffer key = new StringBuffer();
- String year = String.valueOf(cal.get(Calendar.YEAR)).substring(3);
- int month = cal.get(Calendar.MONTH) + 1;
- int date = cal.get(Calendar.DATE);
- int hour = cal.get(Calendar.HOUR_OF_DAY);
- int minute = cal.get(Calendar.MINUTE);
- int second = cal.get(Calendar.SECOND);
- int millisecond = cal.get(Calendar.MILLISECOND);
- // System.out.println(millisecond);
- key.append(prefix).append(year).append(month < 10 ? "0" + month : month).append(date < 10 ? "0" + date : date)
- .append(hour < 10 ? "0" + hour : hour).append(minute < 10 ? "0" + minute : minute).append(
- second < 10 ? "0" + second : second).append(millisecond < 10 ? "0" + millisecond : millisecond)
- .append(randomNumber).append(suffix);
- return key.toString();
- }
- /**
- * <p>
- * Description:[产生具有前缀和后缀的唯一字符串,中间14位+自定义提示表名]
- * </p>
- *
- * @param prefix
- * @param suffix
- * @param gridConfigBean
- * @return
- * @throws Exception
- */
- public static String createUniqueKey(String prefix, String suffix, String prefix_support) {
- String csvName = getI18N(prefix_support);
- if (csvName == null || csvName.trim().length() == 0) {
- throw new CommonException("The ModuleCode of the FormBean is Empty");
- }
- int randomNumber = (int) (Math.random() * 9);
- Calendar cal = Calendar.getInstance();
- StringBuffer key = new StringBuffer();
- String year = String.valueOf(cal.get(Calendar.YEAR)).substring(3);
- int month = cal.get(Calendar.MONTH) + 1;
- int date = cal.get(Calendar.DATE);
- int hour = cal.get(Calendar.HOUR_OF_DAY);
- int minute = cal.get(Calendar.MINUTE);
- int second = cal.get(Calendar.SECOND);
- int millisecond = cal.get(Calendar.MILLISECOND);
- // System.out.println(millisecond);
- key.append(prefix).append(year).append(month < 10 ? "0" + month : month).append(date < 10 ? "0" + date : date)
- .append(hour < 10 ? "0" + hour : hour).append(minute < 10 ? "0" + minute : minute).append(
- second < 10 ? "0" + second : second).append(millisecond < 10 ? "0" + millisecond : millisecond)
- .append(randomNumber).append("——" + csvName).append(suffix);
- return key.toString();
- }
- /**
- * <p>
- * Description:[方法功能中文描述]
- * </p>
- *
- * @param key
- * @return
- */
- private static String getI18N(String key) {
- if (key == null || "".equals(key)) {
- return "null";
- }
- String value = CommonUtils.getLocalizedMsg(key);
- if (value == null) {
- return key;
- }
- return value;
- }
- /**
- * <p>
- * Description: 对query bean中的日期表达式进行转化
- * </p>
- *
- * @param queryBean
- */
- public static void parseQueryDateExpression(QueryBean queryBean) {
- if (queryBean != null) {
- List<ConditionRule> conditionRules = queryBean.getConditionRules();
- if (conditionRules != null) {
- for (ConditionRule rule : conditionRules) {
- // according to the searchwidge.js
- if ("@DateExpression".equals(rule.getExpression())) {
- String field = rule.getField();
- formatDateConditionRule(rule, field);
- if (rule.getAppend() != null) {
- formatDateConditionRule(rule.getAppend(), field);
- }
- }
- }
- }
- }
- }
- /**
- * <p>
- * Description: 对日期类型的查询条件进行转化
- * </p>
- *
- * @param rule
- * @param field
- */
- public static void formatDateConditionRule(ConditionRule rule, String field) {
- Date date = Expression.excute(rule.getValue());
- if (date != null) {
- String formatDate = new SimpleDateFormat("yyyy-MM-dd").format(date);
- rule.setExpression("Date(${" + field + "}) " + rule.getOperator() + " '" + formatDate + "'");
- rule.setField(null);
- }
- else {
- String formatDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date(0));
- rule.setExpression("Date(${" + field + "}) < '" + formatDate + "'");
- rule.setField(null);
- }
- }
- /**
- * <p>
- * Description: 对query bean中的新关键字:当前用户(loginName)、空(is null is not null)进行转化
- * </p>
- *
- * @param queryBean
- */
- public static void parseQuerySpecialKeyWords(QueryBean queryBean) {
- if (queryBean != null) {
- List<ConditionRule> conditionRules = queryBean.getConditionRules();
- if (conditionRules != null) {
- for (ConditionRule rule : conditionRules) {
- String swValue = rule.getValue();
- if (swValue != null && swValue.startsWith("{") && swValue.endsWith("}")) {
- String swValueString = swValue.substring(1, swValue.length() - 1);
- swValueString = StringUtils.trimAllWhitespace(swValueString);
- if (swValueString.equalsIgnoreCase(getLocalizedMsg("common.msg.currentUser"))) {
- rule.setValue(EdiBusinessSessionContext.getLoginName());
- }
- else if (swValueString.equalsIgnoreCase(getLocalizedMsg("common.msg.null"))) {
- rule.setValue(null);
- if (rule.getOperator().equalsIgnoreCase("=")) {
- rule.setOperator("is");
- }
- else if (rule.getOperator().equalsIgnoreCase("<>")) {
- rule.setOperator("is not");
- }
- }
- }
- // }
- }
- }
- }
- }
- /**
- * <p>
- * Description:[方法功能中文描述]
- * </p>
- *
- * @param message
- * @return
- */
- public static Long getMenuId(String message) {
- if (message == null)
- return null;
- String localizedMsg = PropertiesManager.getProperty(message);
- return localizedMsg != null ? Long.valueOf(localizedMsg) : -1L;
- }
- /**
- * <p>
- * Description:[当前日期转换成时间戳]
- * </p>
- *
- * @param message
- * @return
- */
- public static Timestamp dateChangeToTimestamp(Date date) {
- Timestamp timeStamp = new Timestamp(new Date().getTime());
- return timeStamp;
- }
- /**
- * <p>
- * Description:[生成明细行号]
- * </p>
- *
- * @param detailCount 明细数
- * @return
- */
- public static String generateDetailLineNo(Integer detailCount) {
- if (detailCount == null) {
- detailCount = 0;
- }
- return String.valueOf((BusinessConstants.GENERATE_DETAIL_LINE_NO + ++detailCount)).substring(1);
- }
- /**
- * <p>
- * Description:[得到第二天的时间]
- * </p>
- *
- * @param date 日期对象
- * @param formateTemplete 日期格式
- * @return
- */
- public static Date getNextDate(Date date) {
- Calendar cal = Calendar.getInstance();
- cal.add(Calendar.DATE, 1);
- return cal.getTime();
- }
- /**
- * 根据entity Class 得到其中的注解元素 我们可以得到对象的name和数据库中的字段相对应
- *
- * @param entityClass
- * @return
- */
- public static Map<String, String> createEntityColumnMap(Class entityClass) {
- Map<String, String> entityColumnMap = new HashMap<String, String>();
- PropertyDescriptor[] propDescs = PropertyUtils.getPropertyDescriptors(entityClass);
- for (PropertyDescriptor propDesc : propDescs) {
- // 取得注释的column
- Column column = propDesc.getReadMethod().getAnnotation(Column.class);
- if (column != null) {
- String columnName = column.name().toUpperCase();
- String propertyName = propDesc.getName();
- entityColumnMap.put(propertyName, columnName);
- }
- }
- return entityColumnMap;
- }
- /**
- * <p>
- * Description:[通过queyBean生成JoSQL]
- * </p>
- *
- * @param query
- * @param excludeFields 忽略字段
- * @return
- */
- public static String generateJoSQL(QueryBean query, String[] excludeFields) {
- StringBuffer sql = new StringBuffer("select * from #entity where 1=1 ");
- if (query != null) {
- if (query.getConditionRules() != null) {
- out1: for (ConditionRule con : query.getConditionRules()) {
- String filed = con.getField();
- for (String exludeFiled : excludeFields) {
- if (filed.equalsIgnoreCase(exludeFiled)) {
- continue out1;
- }
- }
- String value = con.getValue();
- sql.append("and ").append(filed).append(" ").append(con.getOperator());
- if (con.getOperator().equals("like")) {
- sql.append(" '%").append(value).append("%'");
- }
- else {
- sql.append("\'").append(value).append("\'");
- }
- }
- }
- if (query.getExtraConditionRules() != null) {
- out2: for (ConditionRule con : query.getExtraConditionRules()) {
- String filed = con.getField();
- for (String exludeFiled : excludeFields) {
- if (filed.equalsIgnoreCase(exludeFiled)) {
- continue out2;
- }
- }
- String value = con.getValue();
- sql.append("and ").append(filed).append(" ").append(con.getOperator());
- if (con.getOperator().equals("like")) {
- sql.append(" '%").append(value).append("%'");
- }
- else {
- sql.append("\'").append(value).append("\'");
- }
- }
- }
- }
- return sql.toString();
- }
- /**
- * <p>
- * Description:内存分页查询
- * </p>
- *
- * @param <T> 实体泛型
- * @param entity 实体类型
- * @param datas 数据集
- * @param queryBean 查询实体
- * @param pageNo 页号
- * @param pageSize 页面容量
- * @param excludeFields 过滤参数
- * @return
- */
- public static <T> Page findByJoSQLWithPage(Class<T> entity, Collection<T> datas, QueryBean queryBean, int pageNo,
- int pageSize, String[] excludeFields) {
- if (CollectionUtils.isEmpty(datas)) {
- return null;
- }
- String sql = generateJoSQL(queryBean, excludeFields);
- sql = sql.replaceAll("#entity", entity.getName());
- int start = Page.getStartOfAnyPage(pageNo, pageSize);
- sql = new StringBuffer(sql).append(" limit ").append(start).append(", ").append(pageSize).toString();
- Query query = new Query();
- try {
- query.parse(sql);
- }
- catch (QueryParseException e) {
- throw new UtilsException("parse sql error", e);
- }
- QueryResults qr = new QueryResults();
- try {
- qr = query.execute(datas);
- }
- catch (QueryExecutionException e) {
- throw new UtilsException("mem query error", e);
- }
- List<?> result = qr.getResults();
- Page page = null;
- if (result != null) {
- page = new Page(start, result.size(), datas.size(), pageSize, result);
- }
- else {
- page = new Page(0, 0, 0, pageSize, null);
- }
- return page;
- }
- /**
- * NULL值返回""
- */
- public static String checkNull(String value) {
- if (null == value) {
- return "";
- }
- else {
- return value;
- }
- }
- /**
- * <p>
- * Description:[数值空返回]
- * </p>
- *
- * @param value
- * @return
- */
- public static BigDecimal checkNum(Double value) {
- if (null == value) {
- return BigDecimal.ZERO;
- }
- else {
- return BigDecimal.valueOf(value);
- }
- }
- public static boolean isEmpty(Collection collection) {
- if (collection == null) {
- return true;
- }
- else {
- if (collection.size() == 0) {
- return true;
- }
- else {
- return false;
- }
- }
- }
- /**
- * <p>
- * Description:[方法功能中文描述]
- * </p>
- *
- * @param str
- * @return
- */
- public static boolean isBiaoDian(String str) {
- Pattern patPunc = Pattern.compile("[`~!@#$^&*()=|{}':;',\\[\\].<>/?~!@#¥……&*()——|{}【】‘;:”“'。,、?]");
- boolean flag = patPunc.matcher(str).matches();
- return flag;
- }
- }
|