Commit f2005619 authored by shizhilong's avatar shizhilong

开发工具类和检查道床记录相关提交 --shizhilong

parent a8dd5eb1
......@@ -45,6 +45,19 @@
<groupId>org.jeecgframework.jimureport</groupId>
<artifactId>jimureport-spring-boot-starter</artifactId>
</dependency>
<!-- hutool -->
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.4.0</version>
</dependency>
<!--字符串-->
<dependency>
<groupId>com.belerweb</groupId>
<artifactId>pinyin4j</artifactId>
<version>2.5.1</version>
</dependency>
<!-- 积木报表 mongo redis 支持包
<dependency>
<groupId>org.jeecgframework.jimureport</groupId>
......
......@@ -29,7 +29,7 @@ public class CodeGenerate {
// 表名
String[] tables = {
"t_ek_turnout_use_check",
"t_ek_track_bed_management_check",
};
......
package org.jeecg.modules.checkData.equipmentCheckData.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
import java.util.Date;
/**
* <p>
* 设备检查记录主表接收类
* </p>
*
* @author hkl
* @since 2023-07-07
*/
@Data
public class RecordsMasterCheckDTO {
private static final long serialVersionUID = 1L;
@ApiModelProperty("主键")
private String id;
@ApiModelProperty("创建人")
private String createBy;
@ApiModelProperty("创建日期")
private Date createTime;
@ApiModelProperty("更新人")
private String updateBy;
@ApiModelProperty("更新时间")
private Date updateTime;
@ApiModelProperty("检查批次编号")
private String ekCode;
@ApiModelProperty("工单编号")
private String workCode;
@ApiModelProperty("轨距水平尺编号")
private String gaugeCode;
@ApiModelProperty("检查区间id")
private String subwaySectionId;
@ApiModelProperty("检查区间名称")
private String subwaySectionName;
@ApiModelProperty("所属线路id")
private String lightRailId;
@ApiModelProperty("所属线路名称")
private String lightRailName;
@ApiModelProperty("所属线别id")
private String lineAliasId;
@ApiModelProperty("所属线别名称")
private String lineAliasName;
@ApiModelProperty("起始里程")
private BigDecimal startingMileage;
@ApiModelProperty("终点里程")
private BigDecimal endMileage;
@ApiModelProperty("备注")
private String remark;
@ApiModelProperty("检查人姓名")
private String checkBy;
@ApiModelProperty("检查日期")
private Date checkTime;
@ApiModelProperty("审核人姓名")
private String verifyBy;
@ApiModelProperty("审核时间")
private Date verifyTime;
@ApiModelProperty("是否删除(0:未删除;1:已删除)")
private String delFlag;
}
package org.jeecg.modules.checkData.equipmentCheckData.dto;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import java.util.Date;
/**
* <p>
* 设备检查记录数据-道床使用情况记录数据接收扩展类
* </p>
*
* @author hkl
* @since 2023-07-07
*/
@Data
public class TrackBedManagementCheckDTO {
private static final long serialVersionUID = 1L;
@ApiModelProperty("主键")
private String id;
@ApiModelProperty("创建人")
private String createBy;
@ApiModelProperty("创建日期")
private Date createTime;
@ApiModelProperty("更新人")
private String updateBy;
@ApiModelProperty("更新时间")
private Date updateTime;
@ApiModelProperty("设备检查记录主表id->外键")
private String recordsMasterCheckId;
@ApiModelProperty("道床id->外键")
private String trakBedManagementId;
@ApiModelProperty("检查项目名称")
private String ekProjectName;
@ApiModelProperty("检查项目内容")
private String ekProjectContent;
@ApiModelProperty("检查合格评判标准")
private String ekPeojectTemplate;
@ApiModelProperty("现场检查项目状态(1:合格;2:良好;3:不合格)")
private String ekProjectStatus;
@ApiModelProperty("是否删除(0:未删除,1:已删除)")
private String delFlag;
}
package org.jeecg.modules.checkData.equipmentCheckData.vo;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
import java.util.Date;
/**
* <p>
* 设备检查记录主表返回类
* </p>
*
* @author hkl
* @since 2023-07-07
*/
@Data
public class RecordsMasterCheckVO {
private static final long serialVersionUID = 1L;
@ApiModelProperty("主键")
@TableId("id")
private String id;
@ApiModelProperty("创建人")
@TableField("create_by")
private String createBy;
@ApiModelProperty("创建日期")
@TableField("create_time")
private Date createTime;
@ApiModelProperty("更新人")
@TableField("update_by")
private String updateBy;
@ApiModelProperty("更新时间")
@TableField("update_time")
private Date updateTime;
@ApiModelProperty("检查批次编号")
@TableField("ek_code")
private String ekCode;
@ApiModelProperty("工单编号")
@TableField("work_code")
private String workCode;
@ApiModelProperty("轨距水平尺编号")
@TableField("gauge_code")
private String gaugeCode;
@ApiModelProperty("检查区间id")
@TableField("subway_section_id")
private String subwaySectionId;
@ApiModelProperty("检查区间名称")
@TableField("subway_section_name")
private String subwaySectionName;
@ApiModelProperty("所属线路id")
@TableField("light_rail_id")
private String lightRailId;
@ApiModelProperty("所属线路名称")
@TableField("light_rail_name")
private String lightRailName;
@ApiModelProperty("所属线别id")
@TableField("line_alias_id")
private String lineAliasId;
@ApiModelProperty("所属线别名称")
@TableField("line_alias_name")
private String lineAliasName;
@ApiModelProperty("起始里程")
@TableField("starting_mileage")
private BigDecimal startingMileage;
@ApiModelProperty("终点里程")
@TableField("end_mileage")
private BigDecimal endMileage;
@ApiModelProperty("备注")
@TableField("remark")
private String remark;
@ApiModelProperty("检查人姓名")
@TableField("check_by")
private String checkBy;
@ApiModelProperty("检查日期")
@TableField("check_time")
private Date checkTime;
@ApiModelProperty("审核人姓名")
@TableField("verify_by")
private String verifyBy;
@ApiModelProperty("审核时间")
@TableField("verify_time")
private Date verifyTime;
@ApiModelProperty("是否删除(0:未删除;1:已删除)")
@TableField("del_flag")
private String delFlag;
}
package org.jeecg.modules.checkData.equipmentCheckData.vo;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.Getter;
import lombok.Setter;
import org.jeecg.modules.utils.DicMap;
import java.util.Date;
/**
* <p>
* 设备检查记录数据-道床使用情况记录数据返回扩展类
* </p>
*
* @author hkl
* @since 2023-07-07
*/
@Data
public class TrackBedManagementCheckVO {
private static final long serialVersionUID = 1L;
@ApiModelProperty("主键")
@TableId("id")
private String id;
@ApiModelProperty("创建人")
@TableField("create_by")
private String createBy;
@ApiModelProperty("创建日期")
@TableField("create_time")
private Date createTime;
@ApiModelProperty("更新人")
@TableField("update_by")
private String updateBy;
@ApiModelProperty("更新时间")
@TableField("update_time")
private Date updateTime;
@ApiModelProperty("设备检查记录主表id->外键")
@TableField("records_master_check_id")
private String recordsMasterCheckId;
@ApiModelProperty("道床id->外键")
@TableField("trak_bed_management_id")
private String trakBedManagementId;
@ApiModelProperty("检查项目名称")
@TableField("ek_project_name")
private String ekProjectName;
@ApiModelProperty("检查项目内容")
@TableField("ek_project_content")
private String ekProjectContent;
@ApiModelProperty("检查合格评判标准")
@TableField("ek_peoject_template")
private String ekPeojectTemplate;
@ApiModelProperty("现场检查项目状态(1:合格;2:良好;3:不合格)")
@TableField("ek_project_status")
private String ekProjectStatus;
@ApiModelProperty("现场检查项目状态翻译(1:合格;2:良好;3:不合格)")
private String ekProjectStatusStr;
public String getApprovalStatusStr() {
return DicMap.EK_APPROVAL_STATUS_MAP.get(ekProjectStatus);
}
@ApiModelProperty("是否删除(0:未删除,1:已删除)")
@TableField("del_flag")
private String delFlag;
}
package org.jeecg.modules.utils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Supplier;
/**
* 对象转换
*/
public class BeanCopyUtil extends BeanUtils {
/**
* 集合数据的拷贝
*
* @param sources: 数据源类
* @param target: 目标类::new(eg: UserVO::new)
* @return
*/
public static <S, T> List<T> copyListProperties(List<S> sources, Supplier<T> target) {
return copyListProperties(sources, target, null);
}
/**
* 带回调函数的集合数据的拷贝(可自定义字段拷贝规则)
*
* @param sources: 数据源类
* @param target: 目标类::new(eg: UserVO::new)
* @param callBack: 回调函数
* @return
*/
public static <S, T> List<T> copyListProperties(List<S> sources, Supplier<T> target, BeanCopyUtilCallBack<S, T> callBack) {
List list = new ArrayList<>(sources.size());
for (S source : sources) {
T t = target.get();
copyProperties(source, t);
list.add(t);
if (callBack != null) {
// 回调
callBack.callBack(source, t);
}
}
return list;
}
/**
* 带回调函数的集合数据的拷贝(可自定义字段拷贝规则),如果拷贝过程中发现有数据不符合不想拷贝可以调用以下方法
*
* @param sources: 数据源类
* @param target: 目标类::new(eg: UserVO::new)
* @param callBack: 回调函数
* @return
*/
public static <S, T> List<T> copyListPropertiesPlus(List<S> sources, Supplier<T> target, BeanCopyUtilCallBackPlus<S, T> callBack) {
List list = new ArrayList<>(sources.size());
Boolean flag = true;
for (S source : sources) {
T t = target.get();
copyProperties(source, t);
if (callBack != null) {
// 回调
flag = callBack.callBack(source, t);
}
if(flag) {
list.add(t);
}
flag = true;
}
return list;
}
/**
* 进行拷贝时属性为null的属性
* @param source 源对象
* @param target 目标对象
* @throws BeansException
*/
public static void copyPropertiesIgnoreNullProperties(Object source, Object target) throws BeansException {
Class<?> actualEditable = target.getClass();
PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
for (PropertyDescriptor targetPd : targetPds) {
if (targetPd.getWriteMethod() != null) {
PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
if (sourcePd != null && sourcePd.getReadMethod() != null) {
try {
Method readMethod = sourcePd.getReadMethod();
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(source);
// 这里判断以下value是否为空 当然这里也能进行一些特殊要求的处理 例如绑定时格式转换等等
if (value != null) {
Method writeMethod = targetPd.getWriteMethod();
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
writeMethod.setAccessible(true);
}
writeMethod.invoke(target, value);
}
} catch (Throwable ex) {
throw new FatalBeanException("Could not copy properties from source to target", ex);
}
}
}
}
}
}
package org.jeecg.modules.utils;
/**
* @author admin
*/
@FunctionalInterface
public interface BeanCopyUtilCallBack<S,T> {
/**
* 定义默认回调方法
* @param t
* @param s
*/
void callBack(S t, T s);
}
package org.jeecg.modules.utils;
/**
* @author admin
*/
@FunctionalInterface
public interface BeanCopyUtilCallBackPlus<S,T> {
/**
* 定义默认回调方法
* @param t
* @param s
*/
boolean callBack(S t, T s);
}
package org.jeecg.modules.utils;
import java.io.Serializable;
/**
* 分页
*/
public class CngcPage implements Serializable {
/**
* 页号
*/
private Long page;
/**
* 每页条数
// @JsonProperty("per_page")
*/
private Long perPage;
/**
* 排序字段
*/
private String sort;
/**
* 是否查询总数
*/
private boolean count;
/**
* 排序
*/
private String order;
public Long getPage() {
return page;
}
public void setPage(Long page) {
this.page = page;
}
public Long getPerPage() {
return perPage;
}
public void setPerPage(Long perPage) {
this.perPage = perPage;
}
public boolean isCount() {
return count;
}
public void setCount(boolean count) {
this.count = count;
}
public String getSort() {
return sort;
}
public void setSort(String sort) {
this.sort = sort;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
}
package org.jeecg.modules.utils;
/**
* 公共编码
* @author admin
*/
public class ConstansVariable {
/**
* 状态码为0
*/
public final static String RESPONSE_CODE = "0";
/**
* 值为null
*/
public final static String RESULT_NULL = "null";
/**
* 值为2
*/
public final static int RESULT_TWO = 2;
/**
* 值为“ ”
*/
public final static String RESULT_IS_NULL = " ";
/**
* 值为8
*/
public final static int RESULT_EIGHT = 8;
/**
* 值为\t
*/
public final static String RESULT_BY = "\t";
/**
* 值为 “Bearer”
*/
public final static String BEARER = "Bearer ";
/**
* 资源根节点
*/
public final static String RESOURCE_ROOT_CODE = "0";
}
package org.jeecg.modules.utils;
import java.util.HashMap;
import java.util.Map;
/**
* @author 50519
* 数据字典服务约定俗称的,
* TODO: 后续迁移到redis
*/
public class DicMap {
/**
* 现场检查项目状态(1:合格;2:良好;3:不合格)
*/
public final static String EK_APPROVAL_STATUS = "EK_APPROVAL_STATUS";
/**
* 现场检查项目状态对应的map
*/
public final static HashMap<String,String> EK_APPROVAL_STATUS_MAP = new HashMap<String,String>(){{
put("1","合格");
put("2","良好");
put("3","不合格");
}};
/**
* 路由地址 此路由地址放在最后,最后加载
*
*/
public final static Map<String,HashMap<String,String>> ROUTE_MAP = new HashMap<String,HashMap<String,String>>(){{
put("EK_APPROVAL_STATUS", EK_APPROVAL_STATUS_MAP);
}};
}
package org.jeecg.modules.utils;
import cn.hutool.json.JSONObject;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import java.util.List;
import java.util.Map;
/**
* 封装返回
* @param <T>
*/
public class JsonResult<T> extends ResponseEntity<T> {
//TODO 下方常量为暂时性方案,后期统计完全后,归类到统一枚举或字典内
static final String CONSTANT_TRUE= "true";
static final String QR_CODE_FALSE= "验证码校验失败";
static final String LOGIN_FOBIDDEN = "错误次数太多,15分钟后再尝试登录";
static final String USER_STATUS_UNUSUAL = "用户处于禁用状态";
static final String USER_DEL_FLAG = "用户处于注销状态";
static final String CHANGE_PASSWORD = "密码复杂度不够,需要修改密码!";
public JsonResult(List data,MultiValueMap<String, String> header,String code) {
super((T)data,header,Message.num2HttpStatus(code));
}
public JsonResult(String code, T data) {
super(data, Message.num2HttpStatus(code));
}
public static <T> JsonResult<T> created(T data) {
return new JsonResult("201", data);
}
public static <T> JsonResult<T> success(T data) {
return new JsonResult("200", data);
}
public static <T> JsonResult<T> success(String msg) {
JSONObject json = new JSONObject();
json.putOpt("message", msg);
return new JsonResult("200", json);
}
public static <T> JsonResult<T> success() {
JSONObject json = new JSONObject();
return new JsonResult("200", json);
}
public static <T> JsonResult<T> accepted(T data) {
return new JsonResult("202", data);
}
public static <T> JsonResult<T> noContented() {
return new JsonResult("204",null);
}
public static <T> JsonResult<T> movedPermanently(T data) {
return new JsonResult("301", data);
}
public static <T> JsonResult<T> found(T data) {
return new JsonResult("302", data);
}
public static <T> JsonResult<T> paged(PageUtils data, Map<String, Object> params) {
String str = StringUtil.objectToString(params.get("count"));
if (null != str && CONSTANT_TRUE.equals(str)){
MultiValueMap<String, String> header = new LinkedMultiValueMap<>();
header.add("X-Total-Count", String.valueOf(data.getTotalCount()));
// 因为浏览器的安全策略获取不到header信息,此处将X-Total-Count数据暴露出来
header.add("Access-Control-Expose-Headers","X-Total-Count");
return new JsonResult(data.getList(),header,"200");
}else{
return new JsonResult("200", data.getList());
}
}
public static <T> JsonResult<T> paged(Map<String, Object> map, Map<String, Object> params) {
String str = (String) params.get("count");
if (null != str && CONSTANT_TRUE.equals(str)){
MultiValueMap<String, String> header = new LinkedMultiValueMap<>();
header.add("X-Total-Count", String.valueOf(map.get("total_count")));
// 因为浏览器的安全策略获取不到header信息,此处将X-Total-Count数据暴露出来
header.add("Access-Control-Expose-Headers","X-Total-Count");
return new JsonResult((List)map.get("list"),header,"200");
}else{
return new JsonResult("200", (List)map.get("list"));
}
}
public static <T> JsonResult<T> paged(PageUtils data, CngcPage model) {
Boolean ifCount = model.isCount();
if (null != ifCount && ifCount){
MultiValueMap<String, String> header = new LinkedMultiValueMap<>();
header.add("X-Total-Count", String.valueOf(data.getTotalCount()));
return new JsonResult(data.getList(),header,"200");
}else{
return new JsonResult("200", data.getList());
}
}
public static <T> JsonResult<T> unauthorized(String msg) {
JSONObject json = new JSONObject();
json.putOpt("message", msg);
return new JsonResult("401", json);
}
public static <T> JsonResult<T> notFounded() {
return new JsonResult("404", null);
}
public static <T> JsonResult<T> failMsg() {
return new JsonResult("422", null);
}
public static <T> JsonResult<T> failMsg(String msg) {
JSONObject json = new JSONObject();
json.putOpt("message", msg);
return new JsonResult("422", json);
}
public static <T> JsonResult<T> failMsg(String code ,String msg) {
JSONObject json = new JSONObject();
json.putOpt("message", msg);
return new JsonResult(code, json);
}
public static <T> JsonResult<T> failMsg(T data) {
return new JsonResult("422", data);
}
//2021-10-28 shiruojiang
public static <T> JsonResult<T> qrcodeFail(){
com.alibaba.fastjson.JSONObject obj = new com.alibaba.fastjson.JSONObject();
obj.put("message", QR_CODE_FALSE);
obj.put("qrcode", true);
return new JsonResult("422", obj);
}
public static <T> JsonResult<T> loginForbidden(){
com.alibaba.fastjson.JSONObject obj = new com.alibaba.fastjson.JSONObject();
obj.put("message", LOGIN_FOBIDDEN);
obj.put("qrcode", true);
return new JsonResult("422", obj);
}
public static <T> JsonResult<T> userStatusUnusual(){
com.alibaba.fastjson.JSONObject obj = new com.alibaba.fastjson.JSONObject();
obj.put("message", USER_STATUS_UNUSUAL);
return new JsonResult("422", obj);
}
public static <T> JsonResult<T> userDelFlag(){
com.alibaba.fastjson.JSONObject obj = new com.alibaba.fastjson.JSONObject();
obj.put("message", USER_DEL_FLAG);
return new JsonResult("422", obj);
}
public static <T> JsonResult<T> changePwd(){
com.alibaba.fastjson.JSONObject obj = new com.alibaba.fastjson.JSONObject();
obj.put("message", CHANGE_PASSWORD);
obj.put("changePassword",true);
return new JsonResult("422", obj);
}
}
class Message<T> {
public static HttpStatus num2HttpStatus(String code) {
HttpStatus status = HttpStatus.NOT_FOUND;
for (HttpStatus httpStatus : HttpStatus.values()) {
boolean b = Integer.parseInt(code) == httpStatus.value();
if (b) {
return httpStatus;
}
}
return status;
}
}
/**
* Copyright (c) 中国兵器 All rights reserved.
*
* norincogroup
*
* 版权所有,侵权必究!
*/
package org.jeecg.modules.utils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import java.io.Serializable;
import java.util.List;
/**
* 分页工具类
*
* @author Sun
*/
public class PageUtils implements Serializable {
private static final long serialVersionUID = 1L;
/**
* 总记录数
*/
private int totalCount;
/**
* 每页记录数
*/
private int pageSize;
/**
* 总页数
*/
private int totalPage;
/**
* 当前页数
*/
private int currPage;
/**
* 列表数据
*/
private List<?> list;
/**
* 分页
* @param list 列表数据
* @param totalCount 总记录数
* @param pageSize 每页记录数
* @param currPage 当前页数
*/
public PageUtils(List<?> list, int totalCount, int pageSize, int currPage) {
this.list = list;
this.totalCount = totalCount;
this.pageSize = pageSize;
this.currPage = currPage;
this.totalPage = (int)Math.ceil((double)totalCount/pageSize);
}
/**
* 分页
*/
public PageUtils(IPage<?> page) {
this.list = page.getRecords();
this.totalCount = (int)page.getTotal();
this.pageSize = (int)page.getSize();
this.currPage = (int)page.getCurrent();
this.totalPage = (int)page.getPages();
}
public int getTotalCount() {
return totalCount;
}
public void setTotalCount(int totalCount) {
this.totalCount = totalCount;
}
public int getPageSize() {
return pageSize;
}
public void setPageSize(int pageSize) {
this.pageSize = pageSize;
}
public int getTotalPage() {
return totalPage;
}
public void setTotalPage(int totalPage) {
this.totalPage = totalPage;
}
public int getCurrPage() {
return currPage;
}
public void setCurrPage(int currPage) {
this.currPage = currPage;
}
public List<?> getList() {
return list;
}
public void setList(List<?> list) {
this.list = list;
}
}
package org.jeecg.modules.utils;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import org.apache.commons.lang.StringUtils;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* <p>5
* 公共方法类
* </p>
* <p>
* 提供字符串处理的实用方法集
* </p>
*
* @author
* @version 1.0
*
*/
public class StringUtil {
//TODO 下方常量为暂时性方案,后期统计完全后,归类到统一枚举或字典内
static final String CONSTANT_NULL= "null";
public StringUtil() {
}
public static final String escapeForIntro(String string) {
// String str = escapeHTMLTags(string);
String str = string;
str = replace(str, "\r\n", "<br>");
str = replace(str, "\n", "<br>");
str = replace(str, "'", "\\'");
return replace(str, "\r", "");
}
/**
* 得到非空的字符串,若字符串对象为null,则返回""。
*
* @param objValue
* Object待转换的原字符串对象
* @return String 转换后的字符串
* */
public static String getNotNullStr(Object objValue) {
return (objValue == null ? "" : objValue.toString());
}
/**
* 得到非空的字符串,若字符串为null,则返回""。
*
* @param strValue
* String待转换的原字符串
* @return String 转换后的字符串
* */
public static String getNotNullStr(String strValue) {
return (strValue == null ? "" : strValue.trim());
}
// /**
// * 将中文转化成AscII码以便存入数据库
// *
// * @param s
// * 中文字符串
// * @return 16进制字符串
// */
// public static String ChineseStringToAscii(String s) {
// try {
// CharToByteConverter toByte = CharToByteConverter
// .getConverter("GBK");
// byte[] orig = toByte.convertAll(s.toCharArray());
// char[] dest = new char[orig.length];
// for (int i = 0; i < orig.length; i++)
// dest[i] = (char) (orig[i] & 0xFF);
// return new String(dest);
// } catch (Exception e) {
// System.out.println(e);
// return s;
// }
// }
// /**
// * 将UTF-8转化成AscII码以便存入数据库
// *
// * @param s
// * 中文字符串
// * @return 16进制字符串
// */
// public static String ChineseStringToUTF(String s) {
// try {
// CharToByteConverter toByte = CharToByteConverter
// .getConverter("UTF-8");
// byte[] orig = toByte.convertAll(s.toCharArray());
// char[] dest = new char[orig.length];
// for (int i = 0; i < orig.length; i++)
// dest[i] = (char) (orig[i] & 0xFF);
// return new String(dest);
// } catch (Exception e) {
// System.out.println(e);
// return s;
// }
// }
//
// /**
// * 将AscII字符转换成汉字
// *
// * @param s
// * - ASCII字符串
// * @return 汉字
// */
// public static String AsciiToChineseString(String s) {
// char[] orig = s.toCharArray();
// byte[] dest = new byte[orig.length];
// for (int i = 0; i < orig.length; i++)
// dest[i] = (byte) (orig[i] & 0xFF);
// try {
// ByteToCharConverter toChar = ByteToCharConverter
// .getConverter("GBK");
// return new String(toChar.convertAll(dest));
// } catch (Exception e) {
// System.out.println(e);
// return s;
// }
// }
// /**
// * 使用正则表达式进行字符串内容替换
// * @param regularExpression 正则表达式
// * @param sub 替换的字符串
// * @param input 要替换的字符串
// * @return String 替换后的字符串
// */
// public static synchronized String regexReplace(String regularExpression,
// String sub, String input)
// {
// Pattern pattern = PatternFactory.getPattern(regularExpression);
// Matcher matcher = pattern.matcher(input);
// StringBuffer sb = new StringBuffer();
// while (matcher.find())
// {
// matcher.appendReplacement(sb, sub);
// }
// matcher.appendTail(sb);
// return sb.toString();
// }
/**
* 判断一个字符串中是否包含符合正则表达式定义的匹配条件的子串
*
* @param regularExpression
* - 正则表达式
* @param input
* - 待检查字符串
* @return - 若输入字符串中包含符合正则表达式定义的匹配条件的子串,则返回true,否则返回false
*/
// //正则表达式匹配判断
// public static synchronized boolean exist(String regularExpression, String
// input)
// {
// Pattern pattern = PatternFactory.getPattern(regularExpression);
// Matcher matcher = pattern.matcher(input);
// return matcher.find();
// }
/**
* 用"0"补足一个字符串到指定长度
*
* @param str
* - 源字符串
* @param size
* - 补足后应达到的长度
* @return - 补零后的结果
*/
public static String fillZero(String str, int size) {
String result;
if (str.length() < size) {
char[] s = new char[size - str.length()];
for (int i = 0; i < (size - str.length()); i++) {
s[i] = '0';
}
result = new String(s) + str;
}
else {
result = str;
}
return result;
}
/**
* 根据字符串(文件类型或者多行输入类型)获取字符串数组
*
* @param str1
* String 输入字符串
* @return String[] 返回结果
*/
public static String[] getStrArryByString(String str1) {
if (str1.indexOf(ConstansVariable.RESULT_BY) > 0) {
for (int i = 0; i < str1.length(); i++) {
if ("\t".equals(str1.substring(i, i + 1))) {
str1 = str1.substring(0, i) + " " + str1.substring(i + 1, str1.length());
}
}
}
StringTokenizer stringTokenizer = new StringTokenizer(str1, "\r\n");
String[] strId = new String[stringTokenizer.countTokens()];
int i = 0;
while (stringTokenizer.hasMoreTokens()) {
strId[i] = stringTokenizer.nextToken();
i++;
}
return strId;
}
/**
* 判断一个字符串是否为 NUll 或为空
*
* @param inStr
* inStr
* @return boolean
*/
public static boolean isValid(String inStr) {
if (inStr == null) {
return false;
}
else if ("".equals(inStr)) {
return false;
}
else if (inStr.equals(ConstansVariable.RESULT_NULL)) {
return false;
}
else {
return true;
}
}
/**
* 判断一个字符串是否为 NUll 或为空
*
* inStr
* @return boolean
*/
public static boolean checkNotNull(String str) {
boolean flag = false;
if (str != null && str.trim().length() != 0 && !CONSTANT_NULL.equals(str)) {
flag = true;
}
return flag;
}
/**
* 判断对象是否为空
*
* @param str
* @return
*/
public static boolean isNotEmpty(Object str) {
boolean flag = true;
if (str != null && !"".equals(str)) {
if (str.toString().length() > 0) {
flag = true;
}
}
else {
flag = false;
}
return flag;
}
/**
* 获得指定长度的空格
*
* @param spaceNum
* spaceNum
* @return String
*/
public static String getStrSpace(int spaceNum) {
return getStrWithSameElement(spaceNum, " ");
}
/**
* 获得指定长度的字符串
*
* @param num
* int
* @param element
* String
* @return String
*/
public static String getStrWithSameElement(int num, String element) {
if (num <= 0) {
return "";
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < num; i++) {
sb.append(element);
}
return sb.toString();
}
/**
* 从右或左加空格
*
* @param strIn
* String
* @param totalLength
* int
* @param isRightAlign
* boolean
* @return String
*/
public static String getFillString(String strIn, int totalLength, boolean isRightAlign) {
int spaceLength = 0;
String spaces = null;
String strOut = null;
if (strIn == null) {
strIn = "";
}
spaceLength = totalLength - strIn.length();
if (spaceLength < 0) {
spaceLength = 0;
}
spaces = StringUtil.getStrSpace(spaceLength);
if (isRightAlign) {
strOut = spaces + strIn;
}
else {
strOut = strIn + spaces;
}
return strOut;
}
/**
* 以String类型返回错误抛出的堆栈信息
*
* @param t
* Throwable
* @return String
*/
public static String getStackTrace(Throwable t) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
return sw.toString();
}
/**
* 转换字符串第一个字符为大写
*
* @param str
* String
* @return String
*/
public static String getStrByUpperFirstChar(String str) {
try {
return str.substring(0, 1).toUpperCase() + str.substring(1);
}
catch (Exception e) {
return "";
}
}
/**
* 转换字符串第一个字符为小写
*
* @param str
* String
* @return String
*/
public static String getStrByLowerFirstChar(String str) {
try {
return str.substring(0, 1).toLowerCase() + str.substring(1);
}
catch (Exception e) {
return "";
}
}
/**
* 通过字符串转换成相应的整型,并返回。
*
* @param strValue
* String 待转换的字符串
* @return int 转换完成的整型
* */
public static int getStrToInt(String strValue) {
if (null == strValue) {
return 0;
}
int iValue = 0;
try {
iValue = new Integer(strValue.trim()).intValue();
}
catch (Exception ex) {
iValue = 0;
}
return iValue;
}
/**
* 通过字符串转换成相应的DOUBLE,并返回。
*
* @param strValue
* String 待转换的字符串
* @return double 转换完成的DOUBLE
* */
public static double getStrToDouble(String strValue) {
if (null == strValue) {
return 0;
}
double dValue = 0;
try {
dValue = Double.parseDouble(strValue.trim());
}
catch (Exception ex) {
dValue = 0;
}
return dValue;
}
/**
* 通过字符串转换成相应的短整型,并返回。
*
* @param strValue
* String 待转换的字符串
* @return short 转换完成的短整型
* */
public static short getStrToShort(String strValue) {
if (null == strValue) {
return 0;
}
short iValue = 0;
try {
iValue = new Short(strValue.trim()).shortValue();
}
catch (Exception ex) {
iValue = 0;
}
return iValue;
}
/**
* 通过字符串转换成相应的长整型,并返回。
*
* @param strValue
* String 待转换的字符串
* @return long 转换完成的长整型
* */
public static long getStrToLong(String strValue) {
if (null == strValue) {
return 0;
}
long lValue = 0;
try {
lValue = new Long(strValue.trim()).longValue();
}
catch (Exception ex) {
lValue = 0;
}
return lValue;
}
public static String toLengthForEn(String str, int length) {
if (null != str) {
if (str.length() <= length) {
return str;
}
else {
str = str.substring(0, length - 2);
str = str + "..";
return str;
}
}
else {
return "";
}
}
/**
* 降字符串转换成给定长度的字符串,如超出的话截断,并在最后以两个点结尾
*
* @param str
* String
* @param length
* int
* @return String
*/
public static String toLengthForIntroduce(String str, int length) {
str = delTag(str);
byte[] strByte = str.getBytes();
int byteLength = strByte.length;
char[] charArray;
StringBuffer buff = new StringBuffer();
if (byteLength > (length * ConstansVariable.RESULT_TWO)) {
charArray = str.toCharArray();
int resultLength = 0;
for (int i = 0; i < charArray.length; i++) {
resultLength += String.valueOf(charArray[i]).getBytes().length;
if (resultLength > (length * 2)) {
break;
}
buff.append(charArray[i]);
}
buff.append("..");
str = buff.toString();
}
// str = replace(str, "'", "\\'");
str = replace(str, "\"", "\\\"");
str = replace(str, ",", ",");
return str;
}
public static String delTag(String str) {
str = str + "<>";
StringBuffer buff = new StringBuffer();
int start = 0;
int end = 0;
while (str.length() > 0) {
start = str.indexOf("<");
end = str.indexOf(">");
if (start > 0) {
buff.append(str.substring(0, start));
}
if (end > 0 && end <= str.length()) {
str = str.substring(end + 1, str.length());
}
else {
str = "";
}
}
String result = buff.toString();
while (result.startsWith(ConstansVariable.RESULT_IS_NULL)) {
result = result.substring(result.indexOf(" ") + 1, result.length());
}
return result;
}
public static final String replace(String line, String oldString, String newString) {
if (line == null) {
return null;
}
int i = 0;
if ((i = line.indexOf(oldString, i)) >= 0) {
char[] line2 = line.toCharArray();
char[] newString2 = newString.toCharArray();
int oLength = oldString.length();
StringBuffer buf = new StringBuffer(line2.length);
buf.append(line2, 0, i).append(newString2);
i += oLength;
int j = i;
while ((i = line.indexOf(oldString, i)) > 0) {
buf.append(line2, j, i - j).append(newString2);
i += oLength;
j = i;
}
buf.append(line2, j, line2.length - j);
return buf.toString();
}
return line;
}
/**
* Replace
*/
public static String replaceSource(String source, String oldString, String newString) {
if (source == null) {
return null;
}
StringBuffer output = new StringBuffer();
int lengOfsource = source.length();
int lengOfold = oldString.length();
int posStart = 0;
int pos;
while ((pos = source.indexOf(oldString, posStart)) >= 0) {
output.append(source.substring(posStart, pos));
output.append(newString);
posStart = pos + lengOfold;
}
if (posStart < lengOfsource) {
output.append(source.substring(posStart));
}
return output.toString();
}
/** 此函数前台使用中,请勿随便修改,不然会造成显示混乱(以前修改版本在下方注释中)
*
* @param s
* @return
*/
public static String toHtml(String s) {
s = replaceSource(s, "<", "&lt;");
s = replaceSource(s, ">", "&gt;");
s = replaceSource(s, "\t", " ");
s = replaceSource(s, "\r\n", "\n");
s = replaceSource(s, "\n", "<br>");
// s = Replace(s, " ", "&nbsp;");
s = replaceSource(s, "'", "&#39;");
s = replaceSource(s, "\"", "&quot;");
s = replaceSource(s, "\\", "&#92;");
s = replaceSource(s, "%", "%");
// s = Replace(s, "&", "&amp;");
return s;
}
/** 逆
*/
public static String unHtml(String s) {
// s = Replace(s, "&lt;", "<");
// s = Replace(s, "&gt;", ">");
// s = Replace(s, " ", "\t");
// s = Replace(s, "\n", "\r\n");
s = replaceSource(s, "<br>", "\n");
// s = Replace(s, "&nbsp;", " ");
// s = Replace(s, "&amp;", "&");
// s = Replace(s, "&#39;", "'");
// s = Replace(s, "&#92;", "\\");
// s = Replace(s, "%", "%");
return s;
}
/** 此函数后台使用中,请勿随便修改,不然会造成显示混乱(以前修改版本在下方注释中)*/
public static String toHtmlBack(String s) {
// 显示
s = replaceSource(s, "&", "&amp;");
s = replaceSource(s, "\\", "&#92;");
s = replaceSource(s, "\"", "&quot;");
s = replaceSource(s, "<", "&lt;");
s = replaceSource(s, ">", "&gt;");
s = replaceSource(s, "\t", " ");
s = replaceSource(s, "\r\n", "\n");
// s = Replace(s, "\n", "<br>");
// s = Replace(s, " ", "&nbsp;");
// s = Replace(s, "'", "&#39;");
// s = Replace(s, "%", "%");
return s;
}
/** 逆
*
* @param s
* @return
*/
public static String unHtmlBack(String s) {
s = replaceSource(s, "&lt;", "<");
s = replaceSource(s, "&gt;", ">");
s = replaceSource(s, " ", "\t");
s = replaceSource(s, "\n", "\r\n");
s = replaceSource(s, "<br>", "\n");
s = replaceSource(s, "&nbsp;", " ");
s = replaceSource(s, "&amp;", "&");
s = replaceSource(s, "&#39;", "'");
s = replaceSource(s, "&#92;", "\\");
s = replaceSource(s, "%", "%");
return s;
}
/*
* public static String toHtml(String s) { //显示 s = Replace(s, "&",
* "&amp;"); s = Replace(s, "\\", "&#92;"); s = Replace(s, "\"", "&quot;");
* s = Replace(s, "<", "&lt;"); s = Replace(s, ">", "&gt;"); s = Replace(s,
* "\t", " "); s = Replace(s, "\r\n", "\n"); // s = Replace(s, "\n",
* "<br>"); s = Replace(s, " ", "&nbsp;"); // s = Replace(s, "'", "&#39;");
* // s = Replace(s, "%", "%");
*
* return s; }
*
* public static String unHtml(String s) { s = Replace(s, "&lt;", "<"); s =
* Replace(s, "&gt;", ">"); s = Replace(s, " ", "\t"); s = Replace(s,
* "\n", "\r\n"); s = Replace(s, "<br>", "\n"); s = Replace(s, "&nbsp;",
* " "); s = Replace(s, "&amp;", "&"); s = Replace(s, "&#39;", "'"); s =
* Replace(s, "&#92;", "\\"); s = Replace(s, "%", "%"); return s; }
*/
/**
* 判断是否含有中文,如果含有中文返回ture
*/
public static boolean containsChinese(String str) throws UnsupportedEncodingException {
if (str.length() < (str.getBytes()).length) {
return true;
}
return false;
// for (int i = 0; i < username.length(); i++) {
// String unit=Character.toString(username.charAt(i));
// byte[] unitByte=unit.getBytes("GBK");
// // ((unitByte[0]+256)*256 + (unitByte[1]+256)) <= 0xFEFE)
// if (unitByte.length == 2)
// {
// return true;
// }
// }
// return false;
}
public static boolean isEmpty(String str) {
if (str == null) {
return true;
}
return "".equals(str.trim());
}
public static String[] split(String str1, String str2) {
return StringUtils.split(str1, str2);
}
/**
*
* <br>
* <b>功能:</b>将字符串转成list<br>
* <b>作者:</b>罗泽军<br>
* <b>日期:</b> Oct 28, 2011 <br>
*
* @param exp
* 分割符 如","
* @param value
* @return
*/
public static List<String> stringToList(String value, String exp) {
List<String> resultList = new ArrayList<String>();
String[] vals = split(value, exp);
for (String val : vals) {
resultList.add(val);
}
return resultList;
}
/**
*
* <br>
* <b>功能:</b>数字转换成字符串<br>
* <b>作者:</b>罗泽军<br>
* <b>日期:</b> Jul 30, 2011 <br>
*
* @param arrs
* @return
*/
public static String arrayToString(String[] arrs) {
StringBuffer result = new StringBuffer("");
if (arrs != null && arrs.length > 0) {
for (int i = 0; i < arrs.length; i++) {
if (!"".equals(result.toString())) {
result.append(',');
}
if (arrs[i] != null && !"".equals(arrs[i].trim())) {
result.append(arrs[i]);
}
}
}
return result.toString();
}
/**
*
* <br>
* <b>功能:</b>数字转换成字符串<br>
* <b>作者:</b>罗泽军<br>
* <b>日期:</b> Jul 30, 2011 <br>
*
* @param arrs
* @return
*/
public static String arrayToString(Object[] arrs) {
StringBuffer result = new StringBuffer("");
if (arrs != null && arrs.length > 0) {
for (int i = 0; i < arrs.length; i++) {
if (!"".equals(result.toString())) {
result.append(',');
}
if (arrs[i] != null && !"".equals(arrs[i].toString().trim())) {
result.append(arrs[i]);
}
}
}
return result.toString();
}
public static String left(String str, int length) {
return StringUtils.left(str, length);
}
/**
*
* <br>
* <b>功能:</b>替换回车<br>
* <b>作者:</b>罗泽军<br>
* <b>日期:</b> Oct 26, 2011 <br>
*
* @param str
* @return
*/
public static String replaceHuiche(String str) {
String after = str.replaceAll("\r\n", "");
return after;
}
/**
* 根据输入的长度截取字符串,单个单词超过输入长度的强制加<BR>
* 换行
*
* @param str
* 输入的字符串
* @param len
* 输入的长度
* @return 处理过后的字符串
*/
public static String truncateStr(String str, int len) {
if (str != null && !("").equalsIgnoreCase(str)) {
String[] strs = str.split(" ");
StringBuffer buff = new StringBuffer();
if (strs.length > 0) {
for (int i = 0; i < strs.length; i++) {
StringBuffer temp = new StringBuffer();
while (strs[i].length() > len) {
temp.append(strs[i].substring(0, len) + "<BR>");
strs[i] = strs[i].substring(len);
}
temp.append(strs[i]);
buff.append(temp.toString() + " ");
}
}
return buff.toString();
}
else {
return "";
}
}
public static String truncateStr2(String str, int len) {
if (str != null && !("").equalsIgnoreCase(str) && len != 0) {
String[] strs = str.split(" ");
StringBuffer buff = new StringBuffer();
for (int i = 0; i < strs.length; i++) {
StringBuffer temp = new StringBuffer();
String tempstr = "";
while (strs[i].length() > len) {
tempstr = strs[i].substring(0, len);
tempstr = tempstr.replaceAll(" ", "&nbsp; ");
tempstr = tempstr.replaceAll("<", "&lt; ");
tempstr = tempstr.replaceAll("\n", "<br> ").replaceAll("\"", "&quot; ").replaceAll("'", "&#39; ");
tempstr = tempstr + "<br>";
temp.append(tempstr);
strs[i] = strs[i].substring(len);
}
tempstr = strs[i];
tempstr = tempstr.replaceAll(" ", "&nbsp; ");
tempstr = tempstr.replaceAll("<", "&lt; ");
tempstr = tempstr.replaceAll("\n", "<br> ").replaceAll("\"", "&quot; ").replaceAll("'", "&#39; ");
temp.append(tempstr);
buff.append(temp.toString() + " ");
}
if (buff.length() > 0) {
return buff.toString().substring(0, buff.length() - 1);
} else {
return str;
}
}
else {
return "";
}
}
/**
* 编码转换,从unicode转换为GBK
*
* 输入字符串
* @return str编码转换后的字符串
* @throws UnsupportedEncodingException
*/
public static String UnicodeToGb(String lsSource) throws UnsupportedEncodingException {
String lsDesc = "";
if (lsSource != null && !"".equals(lsSource.trim())) {
byte[] lbProc = lsSource.getBytes("GBK");
lsDesc = new String(lbProc, "ISO8859_1");
}
return lsDesc;
}
/**
* 编码转换,从GBK转换为unicode
*
* 输入字符串
* @return str 编码转换后的字符串
* @throws UnsupportedEncodingException
*/
public static String GbToUnicode(String lsSource) throws UnsupportedEncodingException {
String lsDesc = "";
if (lsSource != null && !"".equals(lsSource.trim())) {
byte[] lbProc = lsSource.getBytes("ISO8859_1");
lsDesc = new String(lbProc, "GBK");
}
return lsDesc;
}
/**
* Escapes a <code>String</code> according the JavaScript string literal
* escaping rules. The resulting string will not be quoted.
*
* <p>
* It escapes both <tt>'</tt> and <tt>"</tt>. In additional it escapes <tt>></tt> as
* <tt>\></tt> (to avoid <tt>&lt;/script></tt>). Furthermore, all characters
* under UCS code point 0x20, that has no dedicated escape sequence in
* JavaScript language, will be replaced with hexadecimal escape (
* <tt>\x<i>XX</i></tt>).
*/
public static String javaScriptStringEnc(String s) {
int ln = s.length();
for (int i = 0; i < ln; i++) {
char c = s.charAt(i);
if (c == '"' || c == '\'' || c == '\\' || c == '>' || c < 0x20) {
StringBuffer b = new StringBuffer(ln + 4);
b.append(s.substring(0, i));
while (true) {
if (c == '"') {
b.append("\\\"");
}
else if (c == '\'') {
b.append("\\'");
}
else if (c == '\\') {
b.append("\\\\");
}
else if (c == '>') {
b.append("\\>");
}
else if (c < 0x20) {
if (c == '\n') {
b.append("\\n");
}
else if (c == '\r') {
b.append("\\r");
}
else if (c == '\f') {
b.append("\\f");
}
else if (c == '\b') {
b.append("\\b");
}
else if (c == '\t') {
b.append("\\t");
}
else {
b.append("\\x");
int x = c / 0x10;
b.append((char) (x < 0xA ? x + '0' : x - 0xA + 'A'));
x = c & 0xF;
b.append((char) (x < 0xA ? x + '0' : x - 0xA + 'A'));
}
}
else {
b.append(c);
}
i++;
if (i >= ln) {
return b.toString();
}
c = s.charAt(i);
}
} // if has to be escaped
} // for each characters
return s;
}
private static StringUtil instance = null;
public static synchronized StringUtil getInstance() {
if (instance == null) {
instance = new StringUtil();
}
return instance;
}
/**
* 将多个连续空格替换为一个,"a b"-->"a b"
*
* @param src
* @return
* @author WilliamLau
* @desc
*/
public static String trimContinuousSpace(String src) {
return src.replaceAll("\\s+", " ");
}
public static String replace(String src, String target, String rWith, int maxCount) {
return StringUtils.replace(src, target, rWith, maxCount);
}
public static boolean equals(String str1, String str2) {
return StringUtils.equals(str1, str2);
}
public static boolean isAlphanumeric(String str) {
return StringUtils.isAlphanumeric(str);
}
public static boolean isNumeric(String str) {
return StringUtils.isNumeric(str);
}
public static String[] stripAll(String[] strs) {
return StringUtils.stripAll(strs);
}
/**
* 将类型Object转换为Integer,Object为空或异常时返还0;
*
* @param o
* @return Integer
*/
public static Integer objectToInteger(Object o) {
try {
if (o != null) {
return Integer.valueOf(o.toString());
}
else {
return 0;
}
}
catch (Exception e) {
return 0;
}
}
/**
* 将类型Object转换为Integer,Object为空或异常时返还0;
*
* @param o
* @return Integer
*/
public static double objectToDouble(Object o) {
try {
if (o != null) {
return Double.parseDouble(o.toString());
}
else {
return 0;
}
}
catch (Exception e) {
return 0;
}
}
/**
* 将类型Object转换为Integer,Object为空或异常时返还0;
*
* @param o
* @return Integer
*/
public static Long objectToLong(Object o) {
try {
if (o != null) {
return Long.valueOf(o.toString());
}
else {
return 0L;
}
}
catch (Exception e) {
return 0L;
}
}
/**
* 将类型Object转换为String,Object为空或异常时返还"";
*
* @param o
* @return String
*/
public static String objectToString(Object o) {
try {
if (o != null) {
return o.toString();
}
else {
return "";
}
}
catch (Exception e) {
return "";
}
}
/**
* 将类型Object转换为date,Object为空或异常时返还"";
*
* @param o
* @return Date
*/
public static Date objectToDate(Object o) {
try {
if (o != null) {
String s = objectToString(o);
return stringToDate(s, "yyyy-MM-dd");
}
else {
return null;
}
}
catch (Exception e) {
return new Date();
}
}
/**
* 格式化时间 把相应字符串时间转化时间的相应格式
*
* @param date
* @param pattern
* @return Date
*/
public static Date stringToDate(String date, String pattern) {
Date reDate = new Date();
if (date != null && !"".equals(date)) {
SimpleDateFormat bartDateFormat = new SimpleDateFormat(pattern);
try {
reDate = bartDateFormat.parse(date);
}
catch (Exception e) {
e.printStackTrace();
}
}
return reDate;
}
public static boolean isInStringArray(String s, String[] ss) {
boolean re = false;
if (ss == null) {
return re;
}
for (int i = 0; i < ss.length; i++) {
if (s != null && s.equals(ss[i])) {
re = true;
return re;
}
}
return re;
}
public static String toFloatNumber(String num) {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(2);
nf.setMinimumFractionDigits(2);
return nf.format(Double.parseDouble(num));
}
public static String toFloatNumber(Double num, int accuracy) {
NumberFormat nf = NumberFormat.getInstance();
nf.setMaximumFractionDigits(accuracy);
nf.setMinimumFractionDigits(accuracy);
return nf.format(num);
}
public static String wcsUnescape(String str) {
str = str.replace("#lt;", "<");
str = str.replace("#gt;", ">");
str = str.replace("#quot;", "\"");
str = str.replace("#amp;amp;", "&");
str = str.replace("#amp;", "&");
str = str.replace("#039;", "'");
return str;
}
/**
*
* <br>
* <b>功能:</b>返回string型的字节数<br>
* <b>作者:</b>罗泽军<br>
* <b>日期:</b> Sep 2, 2011 <br>
*
* @param str
* @return
*/
public static int getByteLength(String str) {
if (str == null) {
return 0;
}
return str.getBytes().length;
}
/**
*
* <br>
* <b>功能:</b>详细的功能描述<br>
* <b>作者:</b>罗泽军<br>
* <b>日期:</b> Sep 2, 2011 <br>
*
* @param str
* 字符
* @param limitLen
* 长度
* @return
*/
public static String getByteStr(String str, int limitLen) {
StringBuffer sb = new StringBuffer();
char[] chars = getNotNullStr(str).toCharArray();
int len = 0;
for (char c : chars) {
len += getByteLength(String.valueOf(c));
if (len <= limitLen) {
sb.append(c);
}
}
return sb.toString();
}
/**
*@param content
* 内容
*@param length
* 指定长度。 超出这个长度就截取字符串。
*@param padding
* 超出长度后,尾加上字符,如"...",可以为空
*@return 返回结果 如果内容没有超出指定的长度。则返回原字符串,超出长度后则截取到指定的长度的内容
*/
public static String subStr(String content, Integer length, String padding) throws UnsupportedEncodingException {
String str = "";
int paddSize = StringUtils.isBlank(padding) ? 0 : padding.length();
// 如果内容为空,或者小于指定的长度。则返回原内容
if (StringUtils.isBlank(content) || content.length() <= length) {
return content;
}
str = content.substring(0, length - paddSize);
if (StringUtils.isNotBlank(padding)) {
str += padding;
}
return str;
}
/**
* 拼接业态id
* @param list
* @return
* @throws UnsupportedEncodingException
*/
public static String joinSysdiGuid(List<?> list) throws UnsupportedEncodingException {
StringBuffer sb = new StringBuffer();
for (Object object : list) {
Class<?> node = object.getClass();
try {
Method method = node.getMethod("getSysdiGuid");
sb.append(method.invoke(object)).append(',');
}
catch (NoSuchMethodException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (InvocationTargetException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return sb.substring(0, sb.length() - 1);
}
/**
* 该方法主要使用正则表达式来判断字符串中是否包含字母
* @author Rice
* @return 返回是否包含
*/
public static boolean judgeContainsStr(String str) {
String regex = ".*[a-zA-Z]+.*";
Matcher m = Pattern.compile(regex).matcher(str);
return m.matches();
}
/**
* 判断字符串str中是否包含字符串inc
* @param str
* @param inc
* @return boolean
* @throws
* @author Rice
* @date 2018年3月8日
*/
public static boolean include(String str, String inc) {
if (str.indexOf(inc) != -1) {
return true;
}
else {
return false;
}
}
public static String getAllPinyin(String hanzi) {
//输出格式设置
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
/**
* 输出大小写设置
*
* LOWERCASE:输出小写
* UPPERCASE:输出大写
*/
format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
/**
* 输出音标设置
*
* WITH_TONE_MARK:直接用音标符(必须设置WITH_U_UNICODE,否则会抛出异常)
* WITH_TONE_NUMBER:1-4数字表示音标
* WITHOUT_TONE:没有音标
*/
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
/**
* 特殊音标ü设置
*
* WITH_V:用v表示ü
* WITH_U_AND_COLON:用"u:"表示ü
* WITH_U_UNICODE:直接用ü
*/
format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
char[] hanYuArr = hanzi.trim().toCharArray();
StringBuilder pinYin = new StringBuilder();
try {
for (int i = 0, len = hanYuArr.length; i < len; i++) {
//匹配是否是汉字
if (Character.toString(hanYuArr[i]).matches("[\\u4E00-\\u9FA5]+")) {
//如果是多音字,返回多个拼音,这里只取第一个
String[] pys = PinyinHelper.toHanyuPinyinStringArray(hanYuArr[i], format);
pinYin.append(pys[0]).append("");
} else {
pinYin.append(hanYuArr[i]).append("");
}
}
} catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
badHanyuPinyinOutputFormatCombination.printStackTrace();
}
return pinYin.toString();
}
public static String getFirstPinYin(String hanyu) {
HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
format.setCaseType(HanyuPinyinCaseType.UPPERCASE);
format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
StringBuilder firstPinyin = new StringBuilder();
char[] hanyuArr = hanyu.trim().toCharArray();
try {
for (int i = 0, len = hanyuArr.length; i < len; i++) {
if(Character.toString(hanyuArr[i]).matches("[\\u4E00-\\u9FA5]+")){
String[] pys = PinyinHelper.toHanyuPinyinStringArray(hanyuArr[i],format);
firstPinyin.append(pys[0].charAt(0));
}else {
firstPinyin.append(hanyuArr[i]);
}
}
} catch (BadHanyuPinyinOutputFormatCombination badHanyuPinyinOutputFormatCombination) {
badHanyuPinyinOutputFormatCombination.printStackTrace();
}
return firstPinyin.toString();
}
}
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment