1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105 |
- /**
- *
- * 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.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.context.BusinessSessionContext;
- import com.behosoft.lis.model.vo.UserVO;
- 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 BusinessUtils extends CommonUtils {
- /**
- * LOGGER
- */
- private static final Log LOGGER = LogFactory.getLog(BusinessUtils.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)
- {
- UserVO userVO = (UserVO)userObject;
-
- loginName = userVO.getUserLoginName();
- }
- }
-
- if( BusinessSessionContext.getLoginName()!=null){
- loginName = String.valueOf(BusinessSessionContext.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", BusinessSessionContext.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", BusinessSessionContext.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 = BusinessSessionContext.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( fieldName.equalsIgnoreCase("deleteFlag")){
- System.out.println(property.getType().getReturnedClass());
- }
- if (value != null && value instanceof BigDecimal) {
- if( property.getType().getReturnedClass()==Integer.class ){
- PropertyUtils.setProperty(instance, fieldName, ((BigDecimal) value).intValue());
- }else if(property.getType().getReturnedClass()==Double.class ){
- PropertyUtils.setProperty(instance, fieldName, ((BigDecimal) value).doubleValue());
- }else if(property.getType().getReturnedClass()==Float.class ){
- PropertyUtils.setProperty(instance, fieldName, ((BigDecimal) value).floatValue());
- }else if(property.getType().getReturnedClass()==Long.class ){
- PropertyUtils.setProperty(instance, fieldName, ((BigDecimal) value).longValue());
- }else{
- PropertyUtils.setProperty(instance, fieldName, ((BigDecimal) value).doubleValue());
- }
- }
- else if (value != null && value instanceof BigInteger) {
- if( property.getType().getReturnedClass()==Integer.class ){
- PropertyUtils.setProperty(instance, fieldName, ((BigInteger) value).intValue());
- }else if(property.getType().getReturnedClass()==Double.class ){
- PropertyUtils.setProperty(instance, fieldName, ((BigInteger) value).doubleValue());
- }else if(property.getType().getReturnedClass()==Float.class ){
- PropertyUtils.setProperty(instance, fieldName, ((BigInteger) value).floatValue());
- }else if(property.getType().getReturnedClass()==Long.class ){
- PropertyUtils.setProperty(instance, fieldName, ((BigInteger) value).longValue());
- }
- else{
- 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(BusinessSessionContext.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;
- }
- }
|