Commit 0dd1527b by songxiang

模板消息发送增加来源分类和类型

parent 8b4e8aee
package com.pcloud.common.core.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import com.pcloud.common.page.PageBean;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
/**
* @描述:数据访问层基础支撑接口. @作者:DiSeng.H
* @创建时间:2016年3月11日,下午4:02:32 @版本:1.0
*/
public interface BaseDao<T> {
/**
* 根据实体对象新增记录.
*
* @param entity
* .
* @return id .
*/
long insert(T entity);
/**
* 批量保存对象.
*
* @param entity
* .
* @return id .
*/
long insert(List<T> list);
/**
* 更新实体对应的记录.
*
* @param entity
* .
* @return
*/
long update(T entity);
/**
* 更新实体对应的记录.
*
* @param entity
* @param sqlId
* @return
*/
long update(T entity, String sqlId);
/**
* 批量更新对象.
*
* @param entity
* .
* @return int .
*/
long update(List<T> list);
/**
* 根据ID查找记录.
*
* @param id
* .
* @return entity .
*/
T getById(long id);
/**
* 根据ID删除记录.
*
* @param id
* .
* @return
*/
long deleteById(long id);
/**
* 分页查询 .
*
* @param pageParam
* 分页参数.
* @param paramMap
* 业务条件查询参数.
* @return
*/
PageBean listPage(PageParam pageParam, Map<String, Object> paramMap);
PageBean listSimplePage(PageParam pageParam, Map<String, Object> paramMap, String sqlId);
PageBean listPage(PageParam pageParam, Map<String, Object> paramMap, String sqlId);
<C> PageBeanNew<C> listPageNew(PageParam pageParam, Map<String, Object> paramMap, String sqlId);
PageBean listPage(PageParam pageParam, Map<String, Object> paramMap, String sqlId, String countSqlId);
/**
* 根据条件查询 listBy: <br/>
*
* @param paramMap
* @return 返回集合
*/
List<T> listBy(Map<String, Object> paramMap);
List<Object> listBy(Map<String, Object> paramMap, String sqlId);
/**
* 根据条件查询 listBy: <br/>
*
* @param paramMap
* @return 返回实体
*/
T getBy(Map<String, Object> paramMap);
Object getBy(Map<String, Object> paramMap, String sqlId);
/**
* 根据序列名称获取下一个值
*
* @return
*/
String getSeqNextValue(String seqName);
SqlSessionTemplate getSessionTemplate();
SqlSession getSqlSession();
}
package com.pcloud.common.core.dao;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import com.pcloud.common.page.PageBean;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
/**
* @描述:数据访问层基础支撑接口. @作者:DiSeng.H
* @创建时间:2016年3月11日,下午4:02:32 @版本:1.0
*/
public interface BaseDao<T> {
/**
* 根据实体对象新增记录.
*
* @param entity .
* @return id .
*/
long insert(T entity);
/**
* 批量保存对象.
*
* @param entity .
* @return id .
*/
long insert(List<T> list);
/**
* 更新实体对应的记录.
*
* @param entity .
* @return
*/
long update(T entity);
/**
* 更新实体对应的记录.
*
* @param entity
* @param sqlId
* @return
*/
long update(T entity, String sqlId);
/**
* 更新实体对应的记录.
*
* @param entity
* @param sqlId
* @param errorMessage 错误消息
* @return
*/
long update(T entity, String sqlId, String errorMessage);
/**
* 批量更新对象.
*
* @param entity .
* @return int .
*/
long update(List<T> list);
/**
* 根据ID查找记录.
*
* @param id .
* @return entity .
*/
T getById(long id);
/**
* 根据ID删除记录.
*
* @param id .
* @return
*/
long deleteById(long id);
/**
* 分页查询 .
*
* @param pageParam 分页参数.
* @param paramMap 业务条件查询参数.
* @return
*/
PageBean listPage(PageParam pageParam, Map<String, Object> paramMap);
PageBean listSimplePage(PageParam pageParam, Map<String, Object> paramMap, String sqlId);
PageBean listPage(PageParam pageParam, Map<String, Object> paramMap, String sqlId);
<C> PageBeanNew<C> listPageNew(PageParam pageParam, Map<String, Object> paramMap, String sqlId);
PageBean listPage(PageParam pageParam, Map<String, Object> paramMap, String sqlId, String countSqlId);
/**
* 根据条件查询 listBy: <br/>
*
* @param paramMap
* @return 返回集合
*/
List<T> listBy(Map<String, Object> paramMap);
List<Object> listBy(Map<String, Object> paramMap, String sqlId);
/**
* 根据条件查询 listBy: <br/>
*
* @param paramMap
* @return 返回实体
*/
T getBy(Map<String, Object> paramMap);
Object getBy(Map<String, Object> paramMap, String sqlId);
/**
* 根据序列名称获取下一个值
*
* @return
*/
String getSeqNextValue(String seqName);
SqlSessionTemplate getSessionTemplate();
SqlSession getSqlSession();
}
package com.pcloud.common.core.dao;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.ibatis.jdbc.SqlRunner;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.druid.pool.DruidDataSource;
import com.pcloud.common.core.mybatis.interceptor.ExecutorInterceptor;
import com.pcloud.common.entity.BaseEntity;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.page.PageBean;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
/**
* @描述:数据访问层基础支撑类. @作者:DiSeng.H
* @创建时间:2016年3月11日,下午4:03:36 @版本:1.0
*/
public abstract class BaseDaoImpl<T extends BaseEntity> implements BaseDao<T> {
protected static final Logger logger = LoggerFactory.getLogger(BaseDaoImpl.class);
public static final String SQL_INSERT = "insert";
public static final String SQL_BATCH_INSERT = "batchInsert";
public static final String SQL_UPDATE = "update";
public static final String SQL_GET_BY_ID = "getById";
public static final String SQL_DELETE_BY_ID = "deleteById";
public static final String SQL_LIST_PAGE = "listPage";
public static final String SQL_LIST_BY = "listBy";
public static final String SQL_COUNT_BY_PAGE_PARAM = "countByPageParam"; // 根据当前分页参数进行统计
/**
* 注入SqlSessionTemplate实例(要求Spring中进行SqlSessionTemplate的配置).<br/>
* 可以调用sessionTemplate完成数据库操作.
*/
@Autowired
protected SqlSessionTemplate sqlSessionTemplate;
@Autowired
protected SqlSessionFactory sqlSessionFactory;
@Autowired
private DruidDataSource druidDataSource;
public SqlSessionTemplate getSessionTemplate() {
return sqlSessionTemplate;
}
public SqlSession getSqlSession() {
return sqlSessionTemplate;
}
public long insert(T t) {
if (t == null)
throw new RuntimeException("T is null");
int result = sqlSessionTemplate.insert(getStatement(SQL_INSERT), t);
if (result <= 0)
throw BizException.DB_INSERT_RESULT_0;
if (t != null && t.getId() != null && result > 0)
return t.getId();
return result;
}
public long insert(List<T> list) {
if (list == null || list.size() <= 0)
return 0;
int result = sqlSessionTemplate.insert(getStatement(SQL_BATCH_INSERT), list);
if (result <= 0)
throw BizException.DB_INSERT_RESULT_0;
return result;
}
public long update(T t) {
if (t == null)
throw new RuntimeException("T is null");
int result = sqlSessionTemplate.update(getStatement(SQL_UPDATE), t);
if (result <= 0)
throw BizException.DB_UPDATE_RESULT_0;
return result;
}
public long update(T t, String sqlId) {
if (t == null)
throw new RuntimeException("T is null");
int result = 0;
try {
result = sqlSessionTemplate.update(getStatement(sqlId), t);
} catch (Exception e) {
logger.error("update fail[" + sqlId + "]:" + e.getMessage(), e);
throw BizException.DB_DML_FAIL;
}
if (result <= 0)
throw BizException.DB_UPDATE_RESULT_0;
return result;
}
public long update(List<T> list) {
if (list == null || list.size() <= 0)
return 0;
int result = 0;
for (int i = 0; i < list.size(); i++) {
this.update(list.get(i));
result += 1;
}
if (result <= 0)
throw BizException.DB_UPDATE_RESULT_0;
return result;
}
public T getById(long id) {
return sqlSessionTemplate.selectOne(getStatement(SQL_GET_BY_ID), id);
}
public long deleteById(long id) {
return (long) sqlSessionTemplate.delete(getStatement(SQL_DELETE_BY_ID), id);
}
public PageBean listPage(PageParam pageParam, Map<String, Object> paramMap, String sqlId) {
if (paramMap == null)
paramMap = new HashMap<String, Object>();
// 获取分页数据集 , 注切勿换成 sessionTemplate 对象
List<Object> list = getSqlSession().selectList(getStatement(sqlId), paramMap,
new RowBounds(pageParam.getPageNum() * pageParam.getNumPerPage(), pageParam.getNumPerPage()));
// 统计总记录数
Object countObject = (Object) getSqlSession().selectOne(getStatement(sqlId),
new ExecutorInterceptor.CountParameter(paramMap));
Long count = Long.valueOf(countObject.toString());
return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), count.intValue(), list);
}
public <C> PageBeanNew<C> listPageNew(PageParam pageParam, Map<String, Object> paramMap, String sqlId) {
if (paramMap == null)
paramMap = new HashMap<String, Object>();
// 获取分页数据集 , 注切勿换成 sessionTemplate 对象
List<C> list = getSqlSession().selectList(getStatement(sqlId), paramMap,
new RowBounds(pageParam.getPageNum() * pageParam.getNumPerPage(), pageParam.getNumPerPage()));
// 统计总记录数
Integer count = getSqlSession().selectOne(getStatement(sqlId),
new ExecutorInterceptor.CountParameter(paramMap));
return new PageBeanNew<C>(pageParam.getPageNum(), pageParam.getNumPerPage(), count, list);
}
public PageBean listPage(PageParam pageParam, Map<String, Object> paramMap, String sqlId, String countSqlId) {
if (paramMap == null)
paramMap = new HashMap<String, Object>();
// 获取分页数据集 , 注切勿换成 sessionTemplate 对象
List<Object> list = getSqlSession().selectList(getStatement(sqlId), paramMap,
new RowBounds(pageParam.getPageNum() * pageParam.getNumPerPage(), pageParam.getNumPerPage()));
// 统计总记录数
Object countObject = getSqlSession().selectOne(getStatement(countSqlId), paramMap);
Long count = Long.valueOf(countObject.toString());
return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), count.intValue(), list);
}
public PageBean listSimplePage(PageParam pageParam, Map<String, Object> paramMap, String sqlId) {
if (paramMap == null)
paramMap = new HashMap<String, Object>();
// 获取分页数据集 , 注切勿换成 sessionTemplate 对象
List<Object> list = getSqlSession().selectList(getStatement(sqlId), paramMap,
new RowBounds(pageParam.getPageNum() * pageParam.getNumPerPage(), pageParam.getNumPerPage() + 1));
return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), list);
}
public PageBean listPage(PageParam pageParam, Map<String, Object> paramMap) {
if (paramMap == null)
paramMap = new HashMap<String, Object>();
// 获取分页数据集 , 注切勿换成 sessionTemplate 对象
List<Object> list = getSqlSession().selectList(getStatement(SQL_LIST_PAGE), paramMap,
new RowBounds(pageParam.getPageNum() * pageParam.getNumPerPage(), pageParam.getNumPerPage()));
// 统计总记录数
Object countObject = (Object) getSqlSession().selectOne(getStatement(SQL_LIST_PAGE),
new ExecutorInterceptor.CountParameter(paramMap));
Long count = Long.valueOf(countObject.toString());
// 是否统计当前分页条件下的数据:1:是,其他为否
Object isCount = paramMap.get("isCount");
if (isCount != null && "1".equals(isCount.toString())) {
Map<String, Object> countResultMap = sqlSessionTemplate.selectOne(getStatement(SQL_COUNT_BY_PAGE_PARAM),
paramMap);
return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), count.intValue(), list,
countResultMap);
} else {
return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), count.intValue(), list);
}
}
@SuppressWarnings({ "rawtypes", "unchecked" })
public List<T> listBy(Map<String, Object> paramMap) {
return (List) this.listBy(paramMap, SQL_LIST_BY);
}
public List<Object> listBy(Map<String, Object> paramMap, String sqlId) {
if (paramMap == null)
paramMap = new HashMap<String, Object>();
return sqlSessionTemplate.selectList(getStatement(sqlId), paramMap);
}
@SuppressWarnings("unchecked")
public T getBy(Map<String, Object> paramMap) {
return (T) this.getBy(paramMap, SQL_LIST_BY);
}
public Object getBy(Map<String, Object> paramMap, String sqlId) {
if (paramMap == null || paramMap.isEmpty())
return null;
return this.getSqlSession().selectOne(getStatement(sqlId), paramMap);
}
public String getStatement(String sqlId) {
String name = this.getClass().getName();
StringBuffer sb = new StringBuffer().append(name).append(".").append(sqlId);
return sb.toString();
}
/**
* 根据序列名称,获取序列值
*/
public String getSeqNextValue(String seqName) {
boolean isClosedConn = false;
// 获取当前线程的连接
Connection connection = this.sqlSessionTemplate.getConnection();
// 获取Mybatis的SQLRunner类
SqlRunner sqlRunner = null;
try {
// 要执行的SQL
String sql = "";
// 数据库驱动类
String driverClass = druidDataSource.getDriver().getClass().getName();
// 不同的数据库,拼接SQL语句
if (driverClass.equals("com.ibm.db2.jcc.DB2Driver")) {
sql = " VALUES " + seqName.toUpperCase() + ".NEXTVAL";
}
if (driverClass.equals("oracle.jdbc.OracleDriver")) {
sql = "SELECT " + seqName.toUpperCase() + ".NEXTVAL FROM DUAL";
}
if (driverClass.equals("com.mysql.jdbc.Driver")) {
sql = "SELECT FUN_SEQ('" + seqName.toUpperCase() + "')";
}
// 如果状态为关闭,则需要从新打开一个连接
if (connection.isClosed()) {
connection = sqlSessionFactory.openSession().getConnection();
isClosedConn = true;
}
sqlRunner = new SqlRunner(connection);
Object[] args = {};
// 执行SQL语句
Map<String, Object> params = sqlRunner.selectOne(sql, args);
for (Object o : params.values()) {
return o.toString();
}
return null;
} catch (Exception e) {
throw BizException.DB_GET_SEQ_NEXT_VALUE_ERROR.newInstance("获取序列出现错误!序列名称:{%s}", seqName);
} finally {
if (isClosedConn) {
sqlRunner.closeConnection();
}
}
}
}
package com.pcloud.common.core.dao;
import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import com.pcloud.common.utils.string.StringUtil;
import org.apache.ibatis.jdbc.SqlRunner;
import org.apache.ibatis.session.RowBounds;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.druid.pool.DruidDataSource;
import com.pcloud.common.core.mybatis.interceptor.ExecutorInterceptor;
import com.pcloud.common.entity.BaseEntity;
import com.pcloud.common.exceptions.BizException;
import com.pcloud.common.page.PageBean;
import com.pcloud.common.page.PageBeanNew;
import com.pcloud.common.page.PageParam;
/**
* @描述:数据访问层基础支撑类. @作者:DiSeng.H
* @创建时间:2016年3月11日,下午4:03:36 @版本:1.0
*/
public abstract class BaseDaoImpl<T extends BaseEntity> implements BaseDao<T> {
protected static final Logger logger = LoggerFactory.getLogger(BaseDaoImpl.class);
public static final String SQL_INSERT = "insert";
public static final String SQL_BATCH_INSERT = "batchInsert";
public static final String SQL_UPDATE = "update";
public static final String SQL_GET_BY_ID = "getById";
public static final String SQL_DELETE_BY_ID = "deleteById";
public static final String SQL_LIST_PAGE = "listPage";
public static final String SQL_LIST_BY = "listBy";
public static final String SQL_COUNT_BY_PAGE_PARAM = "countByPageParam"; // 根据当前分页参数进行统计
/**
* 注入SqlSessionTemplate实例(要求Spring中进行SqlSessionTemplate的配置).<br/>
* 可以调用sessionTemplate完成数据库操作.
*/
@Autowired
protected SqlSessionTemplate sqlSessionTemplate;
@Autowired
protected SqlSessionFactory sqlSessionFactory;
@Autowired
private DruidDataSource druidDataSource;
public SqlSessionTemplate getSessionTemplate() {
return sqlSessionTemplate;
}
public SqlSession getSqlSession() {
return sqlSessionTemplate;
}
public long insert(T t) {
if (t == null)
throw new RuntimeException("T is null");
int result = sqlSessionTemplate.insert(getStatement(SQL_INSERT), t);
if (result <= 0)
throw BizException.DB_INSERT_RESULT_0;
if (t != null && t.getId() != null && result > 0)
return t.getId();
return result;
}
public long insert(List<T> list) {
if (list == null || list.size() <= 0)
return 0;
int result = sqlSessionTemplate.insert(getStatement(SQL_BATCH_INSERT), list);
if (result <= 0)
throw BizException.DB_INSERT_RESULT_0;
return result;
}
public long update(T t) {
if (t == null)
throw new RuntimeException("T is null");
int result = sqlSessionTemplate.update(getStatement(SQL_UPDATE), t);
if (result <= 0)
throw BizException.DB_UPDATE_RESULT_0;
return result;
}
public long update(T t, String sqlId) {
if (t == null)
throw new RuntimeException("T is null");
int result = 0;
try {
result = sqlSessionTemplate.update(getStatement(sqlId), t);
} catch (Exception e) {
logger.error("update fail[" + sqlId + "]:" + e.getMessage(), e);
throw BizException.DB_DML_FAIL;
}
if (result <= 0)
throw BizException.DB_UPDATE_RESULT_0;
return result;
}
public long update(T t, String sqlId, String errorMessage) {
if (t == null)
throw new RuntimeException("T is null");
int result = 0;
try {
result = sqlSessionTemplate.update(getStatement(sqlId), t);
} catch (Exception e) {
logger.error("update fail[" + sqlId + "]:" + e.getMessage(), e);
throw BizException.DB_DML_FAIL;
}
if (result <= 0) {
if (StringUtil.isEmpty(errorMessage))
throw BizException.DB_UPDATE_RESULT_0;
else
throw new BizException(10000, errorMessage);
}
return result;
}
public long update(List<T> list) {
if (list == null || list.size() <= 0)
return 0;
int result = 0;
for (int i = 0; i < list.size(); i++) {
this.update(list.get(i));
result += 1;
}
if (result <= 0)
throw BizException.DB_UPDATE_RESULT_0;
return result;
}
public T getById(long id) {
return sqlSessionTemplate.selectOne(getStatement(SQL_GET_BY_ID), id);
}
public long deleteById(long id) {
return (long) sqlSessionTemplate.delete(getStatement(SQL_DELETE_BY_ID), id);
}
public PageBean listPage(PageParam pageParam, Map<String, Object> paramMap, String sqlId) {
if (paramMap == null)
paramMap = new HashMap<String, Object>();
// 获取分页数据集 , 注切勿换成 sessionTemplate 对象
List<Object> list = getSqlSession().selectList(getStatement(sqlId), paramMap,
new RowBounds(pageParam.getPageNum() * pageParam.getNumPerPage(), pageParam.getNumPerPage()));
// 统计总记录数
Object countObject = (Object) getSqlSession().selectOne(getStatement(sqlId),
new ExecutorInterceptor.CountParameter(paramMap));
Long count = Long.valueOf(countObject.toString());
return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), count.intValue(), list);
}
public <C> PageBeanNew<C> listPageNew(PageParam pageParam, Map<String, Object> paramMap, String sqlId) {
if (paramMap == null)
paramMap = new HashMap<String, Object>();
// 获取分页数据集 , 注切勿换成 sessionTemplate 对象
List<C> list = getSqlSession().selectList(getStatement(sqlId), paramMap,
new RowBounds(pageParam.getPageNum() * pageParam.getNumPerPage(), pageParam.getNumPerPage()));
// 统计总记录数
Integer count = getSqlSession().selectOne(getStatement(sqlId),
new ExecutorInterceptor.CountParameter(paramMap));
return new PageBeanNew<C>(pageParam.getPageNum(), pageParam.getNumPerPage(), count, list);
}
public PageBean listPage(PageParam pageParam, Map<String, Object> paramMap, String sqlId, String countSqlId) {
if (paramMap == null)
paramMap = new HashMap<String, Object>();
// 获取分页数据集 , 注切勿换成 sessionTemplate 对象
List<Object> list = getSqlSession().selectList(getStatement(sqlId), paramMap,
new RowBounds(pageParam.getPageNum() * pageParam.getNumPerPage(), pageParam.getNumPerPage()));
// 统计总记录数
Object countObject = getSqlSession().selectOne(getStatement(countSqlId), paramMap);
Long count = Long.valueOf(countObject.toString());
return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), count.intValue(), list);
}
public PageBean listSimplePage(PageParam pageParam, Map<String, Object> paramMap, String sqlId) {
if (paramMap == null)
paramMap = new HashMap<String, Object>();
// 获取分页数据集 , 注切勿换成 sessionTemplate 对象
List<Object> list = getSqlSession().selectList(getStatement(sqlId), paramMap,
new RowBounds(pageParam.getPageNum() * pageParam.getNumPerPage(), pageParam.getNumPerPage() + 1));
return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), list);
}
public PageBean listPage(PageParam pageParam, Map<String, Object> paramMap) {
if (paramMap == null)
paramMap = new HashMap<String, Object>();
// 获取分页数据集 , 注切勿换成 sessionTemplate 对象
List<Object> list = getSqlSession().selectList(getStatement(SQL_LIST_PAGE), paramMap,
new RowBounds(pageParam.getPageNum() * pageParam.getNumPerPage(), pageParam.getNumPerPage()));
// 统计总记录数
Object countObject = (Object) getSqlSession().selectOne(getStatement(SQL_LIST_PAGE),
new ExecutorInterceptor.CountParameter(paramMap));
Long count = Long.valueOf(countObject.toString());
// 是否统计当前分页条件下的数据:1:是,其他为否
Object isCount = paramMap.get("isCount");
if (isCount != null && "1".equals(isCount.toString())) {
Map<String, Object> countResultMap = sqlSessionTemplate.selectOne(getStatement(SQL_COUNT_BY_PAGE_PARAM),
paramMap);
return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), count.intValue(), list,
countResultMap);
} else {
return new PageBean(pageParam.getPageNum(), pageParam.getNumPerPage(), count.intValue(), list);
}
}
@SuppressWarnings({"rawtypes", "unchecked"})
public List<T> listBy(Map<String, Object> paramMap) {
return (List) this.listBy(paramMap, SQL_LIST_BY);
}
public List<Object> listBy(Map<String, Object> paramMap, String sqlId) {
if (paramMap == null)
paramMap = new HashMap<String, Object>();
return sqlSessionTemplate.selectList(getStatement(sqlId), paramMap);
}
@SuppressWarnings("unchecked")
public T getBy(Map<String, Object> paramMap) {
return (T) this.getBy(paramMap, SQL_LIST_BY);
}
public Object getBy(Map<String, Object> paramMap, String sqlId) {
if (paramMap == null || paramMap.isEmpty())
return null;
return this.getSqlSession().selectOne(getStatement(sqlId), paramMap);
}
public String getStatement(String sqlId) {
String name = this.getClass().getName();
StringBuffer sb = new StringBuffer().append(name).append(".").append(sqlId);
return sb.toString();
}
/**
* 根据序列名称,获取序列值
*/
public String getSeqNextValue(String seqName) {
boolean isClosedConn = false;
// 获取当前线程的连接
Connection connection = this.sqlSessionTemplate.getConnection();
// 获取Mybatis的SQLRunner类
SqlRunner sqlRunner = null;
try {
// 要执行的SQL
String sql = "";
// 数据库驱动类
String driverClass = druidDataSource.getDriver().getClass().getName();
// 不同的数据库,拼接SQL语句
if (driverClass.equals("com.ibm.db2.jcc.DB2Driver")) {
sql = " VALUES " + seqName.toUpperCase() + ".NEXTVAL";
}
if (driverClass.equals("oracle.jdbc.OracleDriver")) {
sql = "SELECT " + seqName.toUpperCase() + ".NEXTVAL FROM DUAL";
}
if (driverClass.equals("com.mysql.jdbc.Driver")) {
sql = "SELECT FUN_SEQ('" + seqName.toUpperCase() + "')";
}
// 如果状态为关闭,则需要从新打开一个连接
if (connection.isClosed()) {
connection = sqlSessionFactory.openSession().getConnection();
isClosedConn = true;
}
sqlRunner = new SqlRunner(connection);
Object[] args = {};
// 执行SQL语句
Map<String, Object> params = sqlRunner.selectOne(sql, args);
for (Object o : params.values()) {
return o.toString();
}
return null;
} catch (Exception e) {
throw BizException.DB_GET_SEQ_NEXT_VALUE_ERROR.newInstance("获取序列出现错误!序列名称:{%s}", seqName);
} finally {
if (isClosedConn) {
sqlRunner.closeConnection();
}
}
}
}
package com.pcloud.common.core.dto;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* 模板消息dto
* @author 作者 : lili
* @date 创建时间:2016年11月17日 下午12:03:48
* @version 1.0
* @return
*/
public class TemplateMessageDto implements Serializable {
/**
*
*/
private static final long serialVersionUID = -4132417523244980195L;
/**
* 场景编码值
*/
private String sceneCode;
/**
* 接收消息的当事人ID
*/
private Long receivePartyId;
/**
* 成员账号接收人
*/
private List<Long> receiveMemberPartyIds;
/**
* 接收消息角色(CHANNEL/AGENT/MERCHANT/ADVISER)
*/
private String receivePartyRole;
/**
* 公众号所属当事人ID
*/
private Long sendPartyId;
/**
* 公众号所属当事人角色(CHANNEL/AGENT)
*/
private String sendPartyRole;
/**
* 微信用户
*/
private Long wechatUserId;
/**
* openId
*/
private String openId;
/**
* 昵称
*/
private String nickName;
/**
* url
*/
private String url;
/**
* 参数
*/
private Map<String, String> temParam;
/**
* 发送类型(0: 通过wechatUserId 1 :通过openId 及昵称 2.通过当事人标识)
*/
private String sendType;
/**
* 公众号标识
*/
private Long accountSettingId;
/**
* 是否为应用
*/
private Boolean isApp;
/**
* 应用类型
*/
private String appType;
public Long getAccountSettingId() {
return accountSettingId;
}
public void setAccountSettingId(Long accountSettingId) {
this.accountSettingId = accountSettingId;
}
public String getSceneCode() {
return sceneCode;
}
public void setSceneCode(String sceneCode) {
this.sceneCode = sceneCode;
}
public Long getWechatUserId() {
return wechatUserId;
}
public void setWechatUserId(Long wechatUserId) {
this.wechatUserId = wechatUserId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String> getTemParam() {
return temParam;
}
public void setTemParam(Map<String, String> temParam) {
this.temParam = temParam;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getSendType() {
return sendType;
}
public void setSendType(String sendType) {
this.sendType = sendType;
}
public Long getReceivePartyId() {
return receivePartyId;
}
public void setReceivePartyId(Long receivePartyId) {
this.receivePartyId = receivePartyId;
}
public String getReceivePartyRole() {
return receivePartyRole;
}
public void setReceivePartyRole(String receivePartyRole) {
this.receivePartyRole = receivePartyRole;
}
public Long getSendPartyId() {
return sendPartyId;
}
public void setSendPartyId(Long sendPartyId) {
this.sendPartyId = sendPartyId;
}
public String getSendPartyRole() {
return sendPartyRole;
}
public void setSendPartyRole(String sendPartyRole) {
this.sendPartyRole = sendPartyRole;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public Boolean getIsApp() {
return isApp;
}
public void setIsApp(Boolean isApp) {
this.isApp = isApp;
}
public String getAppType() {
return appType;
}
public void setAppType(String appType) {
this.appType = appType;
}
public List<Long> getReceiveMemberPartyIds() {
return receiveMemberPartyIds;
}
public void setReceiveMemberPartyIds(List<Long> receiveMemberPartyIds) {
this.receiveMemberPartyIds = receiveMemberPartyIds;
}
@Override
public String toString() {
return "TemplateMessageDto [sceneCode=" + sceneCode + ", receivePartyId=" + receivePartyId
+ ", receiveMemberPartyIds=" + receiveMemberPartyIds + ", receivePartyRole=" + receivePartyRole
+ ", sendPartyId=" + sendPartyId + ", sendPartyRole=" + sendPartyRole + ", wechatUserId=" + wechatUserId
+ ", openId=" + openId + ", nickName=" + nickName + ", url=" + url + ", temParam=" + temParam
+ ", sendType=" + sendType + ", accountSettingId=" + accountSettingId + ", isApp=" + isApp
+ ", appType=" + appType + "]";
}
}
package com.pcloud.common.core.dto;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
* 模板消息dto
*
* @author 作者 : lili
* @version 1.0
* @date 创建时间:2016年11月17日 下午12:03:48
* @return
*/
public class TemplateMessageDto implements Serializable {
/**
*
*/
private static final long serialVersionUID = -4132417523244980195L;
/**
* 场景编码值
*/
private String sceneCode;
/**
* 接收消息的当事人ID
*/
private Long receivePartyId;
/**
* 成员账号接收人
*/
private List<Long> receiveMemberPartyIds;
/**
* 接收消息角色(CHANNEL/AGENT/MERCHANT/ADVISER)
*/
private String receivePartyRole;
/**
* 公众号所属当事人ID
*/
private Long sendPartyId;
/**
* 公众号所属当事人角色(CHANNEL/AGENT)
*/
private String sendPartyRole;
/**
* 微信用户
*/
private Long wechatUserId;
/**
* openId
*/
private String openId;
/**
* 昵称
*/
private String nickName;
/**
* url
*/
private String url;
/**
* 参数
*/
private Map<String, String> temParam;
/**
* 发送类型(0: 通过wechatUserId 1 :通过openId 及昵称 2.通过当事人标识)
*/
private String sendType;
/**
* 公众号标识
*/
private Long accountSettingId;
/**
* 是否为应用
*/
private Boolean isApp;
/**
* 应用类型
*/
private String appType;
/**
* 消息来源分类
*/
private String fromCategory;
public String getFromCategory() {
return fromCategory;
}
public void setFromCategory(String fromCategory) {
this.fromCategory = fromCategory;
}
public Long getAccountSettingId() {
return accountSettingId;
}
public void setAccountSettingId(Long accountSettingId) {
this.accountSettingId = accountSettingId;
}
public String getSceneCode() {
return sceneCode;
}
public void setSceneCode(String sceneCode) {
this.sceneCode = sceneCode;
}
public Long getWechatUserId() {
return wechatUserId;
}
public void setWechatUserId(Long wechatUserId) {
this.wechatUserId = wechatUserId;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public Map<String, String> getTemParam() {
return temParam;
}
public void setTemParam(Map<String, String> temParam) {
this.temParam = temParam;
}
public String getOpenId() {
return openId;
}
public void setOpenId(String openId) {
this.openId = openId;
}
public String getSendType() {
return sendType;
}
public void setSendType(String sendType) {
this.sendType = sendType;
}
public Long getReceivePartyId() {
return receivePartyId;
}
public void setReceivePartyId(Long receivePartyId) {
this.receivePartyId = receivePartyId;
}
public String getReceivePartyRole() {
return receivePartyRole;
}
public void setReceivePartyRole(String receivePartyRole) {
this.receivePartyRole = receivePartyRole;
}
public Long getSendPartyId() {
return sendPartyId;
}
public void setSendPartyId(Long sendPartyId) {
this.sendPartyId = sendPartyId;
}
public String getSendPartyRole() {
return sendPartyRole;
}
public void setSendPartyRole(String sendPartyRole) {
this.sendPartyRole = sendPartyRole;
}
public String getNickName() {
return nickName;
}
public void setNickName(String nickName) {
this.nickName = nickName;
}
public Boolean getIsApp() {
return isApp;
}
public void setIsApp(Boolean isApp) {
this.isApp = isApp;
}
public String getAppType() {
return appType;
}
public void setAppType(String appType) {
this.appType = appType;
}
public List<Long> getReceiveMemberPartyIds() {
return receiveMemberPartyIds;
}
public void setReceiveMemberPartyIds(List<Long> receiveMemberPartyIds) {
this.receiveMemberPartyIds = receiveMemberPartyIds;
}
@Override
public String toString() {
return "TemplateMessageDto [sceneCode=" + sceneCode + ", receivePartyId=" + receivePartyId
+ ", receiveMemberPartyIds=" + receiveMemberPartyIds + ", receivePartyRole=" + receivePartyRole
+ ", sendPartyId=" + sendPartyId + ", sendPartyRole=" + sendPartyRole + ", wechatUserId=" + wechatUserId
+ ", openId=" + openId + ", nickName=" + nickName + ", url=" + url + ", temParam=" + temParam
+ ", sendType=" + sendType + ", accountSettingId=" + accountSettingId + ", isApp=" + isApp
+ ", appType=" + appType + "]";
}
}
......@@ -2,6 +2,7 @@ package com.pcloud.common.utils;
import java.util.List;
import com.pcloud.common.page.PageBeanNew;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
......@@ -9,56 +10,78 @@ import org.springframework.beans.BeanUtils;
import com.google.common.collect.Lists;
/**
*
*
* @author:songx
* @date:2018年8月24日,下午2:18:40
*/
public class BeanNewUtils {
private static final Logger LOGGER = LoggerFactory.getLogger(BeanNewUtils.class);
private static final Logger LOGGER = LoggerFactory.getLogger(BeanNewUtils.class);
/**
* 实体类之间的转换
*
* @param source
* 来源
* @param clazz
* 目标对象
* @return
*/
public static <T> T copyProperties(Object source, Class<T> clazz) {
if (source == null) {
return null;
}
T t = null;
try {
t = clazz.newInstance();
} catch (Exception e) {
LOGGER.error("clazz newInstance is error:" + e.getMessage(), e);
}
BeanUtils.copyProperties(source, t);
return t;
}
/**
* 实体类之间的转换
*
* @param source 来源
* @param clazz 目标对象
* @return
*/
public static <T> T copyProperties(Object source, Class<T> clazz) {
if (source == null) {
return null;
}
T t = null;
try {
t = clazz.newInstance();
} catch (Exception e) {
LOGGER.error("clazz newInstance is error:" + e.getMessage(), e);
}
BeanUtils.copyProperties(source, t);
return t;
}
/**
* 实体类之间的转换
*
* @param sources
* 来源
* @param clazz
* 目标对象
* @return
*/
public static <T> List<T> copyProperties(List<?> sources, Class<T> clazz) {
if (ListUtils.isEmpty(sources)) {
return null;
}
List<T> results = Lists.newArrayList();
for (Object source : sources) {
results.add(copyProperties(source, clazz));
}
return results;
}
/**
* 实体类之间的转换
*
* @param sources 来源
* @param clazz 目标对象
* @return
*/
public static <T> List<T> copyProperties(List<?> sources, Class<T> clazz) {
if (ListUtils.isEmpty(sources)) {
return null;
}
List<T> results = Lists.newArrayList();
for (Object source : sources) {
results.add(copyProperties(source, clazz));
}
return results;
}
/**
* 分页结果的实体类之间的转换
*
* @param source
* @param clazz
* @param <T>
* @return
*/
public static <T> PageBeanNew<T> copyProperties(PageBeanNew<?> source, Class<T> clazz) {
if (source == null) {
return null;
}
List<?> recordList = source.getRecordList();
PageBeanNew<T> result = new PageBeanNew<T>();
result.setCurrentPage(source.getCurrentPage());
result.setNumPerPage(source.getNumPerPage());
result.setPageCount(source.getPageCount());
result.setTotalCount(source.getTotalCount());
source.setBeginPageIndex(source.getBeginPageIndex());
source.setEndPageIndex(source.getEndPageIndex());
if (ListUtils.isEmpty(recordList)) {
result.setRecordList(Lists.newArrayList());
return result;
}
result.setRecordList(copyProperties(recordList, clazz));
return result;
}
}
......@@ -20,13 +20,38 @@ import com.pcloud.common.utils.string.StringUtil;
*/
public class LocalDateUtils {
private static final DateTimeFormatter TIME = DateTimeFormatter.ofPattern("HHmmss");
private static final DateTimeFormatter SHORT_MILLISECOND = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
private static final DateTimeFormatter SHORT_DATETIME = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
private static final DateTimeFormatter DATETIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private static final DateTimeFormatter SHORT_DATE = DateTimeFormatter.ofPattern("yyyyMMdd");
private static final DateTimeFormatter DATE = DateTimeFormatter.ofPattern("yyyy-MM-dd");
/**
* 获取当前的日期字符串(yyyy-MM-dd)
*
* @return
*/
public static String getDateNow() {
return LocalDate.now().toString();
return LocalDate.now().format(DATE);
}
/**
* 获取当前的日期字符串(yyyyMMdd)
*
* @return
*/
public static String getShortDateNow() {
return LocalDate.now().format(SHORT_DATE);
}
/**
* 获取当前的时间字符串(HHmmss)
*
* @return
*/
public static String getShortTimeNow() {
return LocalDateTime.now().format(TIME);
}
/**
......@@ -35,7 +60,16 @@ public class LocalDateUtils {
* @return
*/
public static String getDateTimeNow() {
return LocalDateTime.now().withNano(0).toString().replace("T", " ");
return LocalDateTime.now().format(DATETIME);
}
/**
* 获取当前的日期字符串(yyyyMMddHHmmss)
*
* @return
*/
public static String getShortDateTimeNow() {
return LocalDateTime.now().format(SHORT_DATETIME);
}
/**
......@@ -44,8 +78,7 @@ public class LocalDateUtils {
* @return
*/
public static String getYmdhmss() {
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmssSSS");
return LocalDateTime.now().format(formatter);
return LocalDateTime.now().format(SHORT_MILLISECOND);
}
/**
......@@ -65,7 +98,10 @@ public class LocalDateUtils {
* @return
*/
public static String convertToString(LocalDateTime localDateTime) {
return localDateTime.withNano(0).toString().replace("T", " ");
if (localDateTime == null) {
return null;
}
return localDateTime.format(DATETIME);
}
/**
......
package com.pcloud.common.utils;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.MapUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.pcloud.common.page.PageBeanNew;
/**
* 返回结果工具类
*
* @author:songx
* @date:2018年8月8日,下午2:09:16
*/
public class ResultUtils {
/**
* 集合查询结果判断
*
* @param lists
* @return
*/
public static <T> List<T> list(List<T> lists) {
if (!ListUtils.isEmpty(lists)) {
return lists;
}
return Lists.newArrayList();
}
/**
* map查询结果判断
*
* @param lists
* @return
*/
public static <K, V> Map<K, V> map(Map<K, V> map) {
if (!MapUtils.isEmpty(map)) {
return map;
}
return Maps.newHashMap();
}
/**
* 分页查询结果判断
*
* @param pageBeanNew
* @return
*/
public static <T> PageBeanNew<T> pageBeanNew(PageBeanNew<T> pageBeanNew, Integer currentPage, Integer numPerPage) {
if (pageBeanNew != null) {
return pageBeanNew;
}
return new PageBeanNew<T>(currentPage, numPerPage, 0, Lists.newArrayList());
}
}
package com.pcloud.common.utils;
import java.util.List;
import java.util.Map;
import org.apache.commons.collections.MapUtils;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.pcloud.common.page.PageBeanNew;
/**
* 返回结果工具类
*
* @author:songx
* @date:2018年8月8日,下午2:09:16
*/
public class ResultUtils {
/**
* 集合查询结果判断
*
* @param lists
* @return
*/
public static <T> List<T> list(List<T> lists) {
if (!ListUtils.isEmpty(lists)) {
return lists;
}
return Lists.newArrayList();
}
/**
* map查询结果判断
*
* @param lists
* @return
*/
public static <K, V> Map<K, V> map(Map<K, V> map) {
if (!MapUtils.isEmpty(map)) {
return map;
}
return Maps.newHashMap();
}
/**
* 分页查询结果判断
*
* @param pageBeanNew
* @return
*/
public static <T> PageBeanNew<T> pageBeanNew(PageBeanNew<T> pageBeanNew, Integer currentPage, Integer numPerPage) {
if (pageBeanNew != null) {
return pageBeanNew;
}
return new PageBeanNew<T>(currentPage, numPerPage, 0, Lists.newArrayList());
}
}
package com.pcloud.common.utils.string;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.pcloud.common.exceptions.BizException;
/**
* @描述:字符串工具类
* @作者:DiSeng.H
* @创建时间:2016年3月10日,上午11:49:07 @版本:1.0
*/
public class StringUtil extends StringUtilParent {
/**
* 判断字符串是否为空
*
* @param str
* @return
*/
public static boolean isNotNull(String str) {
if (str != null && !"".equals(str.trim())) {
return true;
} else {
return false;
}
}
/**
* 判断对象是否为空
*
* @param str
* @return
*/
public static boolean isNotNull(Object obj) {
if (obj != null && obj.toString() != null && !"".equals(obj.toString().trim())) {
return true;
} else {
return false;
}
}
/**
* 判断字符串是否为空(自动截取首尾空白)
*
* @param str
* 源字符串
* @return
*/
public static boolean isEmpty(String str) {
return isEmpty(str, true);
}
/**
* 判断字符串是否为空
*
* @param str
* 源字符串
* @param trim
* 是否截取首尾空白
* @return
*/
public static boolean isEmpty(String str, boolean trim) {
return str == null ? true : ("".equals(str.trim()) || "null".equals(str.trim()));
}
/**
* 判断数组是否为空
*
* @param str
* @return
*/
public static boolean isEmpty(String[] strs) {
return strs == null ? true : strs.length == 0;
}
/**
* @param str
* the string need to be parsed
* @param delim
* the delimiter to seperate created by zqf at 6/1/2013
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static String[] parseToArray(String str, String delim) {
ArrayList arr = new ArrayList();
StringTokenizer st = new StringTokenizer(str, delim);
while (st.hasMoreTokens()) {
arr.add(st.nextToken());
}
String[] ret = new String[arr.size()];
for (int i = 0; i < arr.size(); i++) {
ret[i] = (String) arr.get(i);
}
return ret;
}
/**
* replace a old substring with rep in str
*
* @param str
* the string need to be replaced
* @param old
* the string need to be removed
* @param rep
* the string to be inserted
* @return string replaced
*/
public static String replace(String str, String old, String rep) {
if ((str == null) || (old == null) || (rep == null)) {// if one is null
// return ""
return "";
}
int index = str.indexOf(old);
if ((index < 0) || "".equals(old)) { // if no old string found or
// nothing to replace,return the
// origin
return str;
}
StringBuffer strBuf = new StringBuffer(str);
while (index >= 0) { // found old part
strBuf.delete(index, index + old.length());
strBuf.insert(index, rep);
index = strBuf.toString().indexOf(old);
}
return strBuf.toString();
}
/**
* 带逗号分隔的数字转换为NUMBER类型
*
* @param str
* @return
* @throws ParseException
*/
public static Number stringToNumber(String str) throws ParseException {
if (str == null || "".equals(str)) {
return null;
}
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator('.');
dfs.setGroupingSeparator(',');
dfs.setMonetaryDecimalSeparator('.');
DecimalFormat df = new DecimalFormat("###,###,###,###.##", dfs);
return df.parse(str);
}
public static String getExtensionName(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot > -1) && (dot < (filename.length() - 1))) {
return filename.substring(dot + 1);
}
}
return filename;
}
/**
* 用于字符串替换
*
* @param target
* 目标对象 需要替换的字符串
* @param replacement
* 要替换的字符串
* @param value
* 替换的值
* @return
*/
public static String replacement(String target, String replacement, String value) {
if (target != null)
return target.replace(replacement, value);
return null;
}
/**
* 判断字符串是否为数字
*
* @param str
* @return
*/
public static boolean isNumeric(String str) {
if (str == null || str.length() == 0) {
return false;
}
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
/**
* 计算指定时间与当前时间的差
*
* @param date
* @return
*/
public static String convDateToString(Date date) {
Long time = new Date().getTime() - date.getTime();
Long min = time / 1000 / 60;
if (min < 5) {
return "刚刚";
} else if (min >= 5 && min < 60) {
return min + "分钟之前";
} else if (min >= 60 && min < 1440) {
return min / 60 + "小时之前";
} else if (min >= 1440 && min < 10080) {
return min / 60 / 24 + "天之前";
} else if (min >= 10080 && min < 40320) {
return min / 60 / 24 / 7 + "周之前";
} else if (min >= 40320 && min < 525600) {
return min / 60 / 24 / 7 / 4 + "月之前";
} else if (min >= 525600) {
return min / 60 / 24 / 365 + "年之前";
}
return null;
}
/**
* @description 获取当前服务器日期
* @return
*/
public static String getCurrdate(String formatStr) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat(formatStr);
String mDateTime = formatter.format(cal.getTime());
return mDateTime;
}
/**
* 将Object值转换成Double类型
*
* @param value
* @return
*/
public static double getDoubleByObj(Object value) {
if (value == null) {
return 0;
}
return Double.valueOf(String.valueOf(value));
}
/**
* 将Object值转换成Float类型
*
* @param value
* @return
*/
public static float getFloatByObj(Object value) {
if (value == null) {
return 0;
}
return Float.valueOf(String.valueOf(value));
}
/**
* 将Object值转换成Integer类型
*
* @param value
* @return
*/
public static Integer getIntegerByObj(Object value) {
if (value == null) {
return 0;
}
return Integer.valueOf(String.valueOf(value));
}
/**
* 解析字符串 ---> 去掉字符串中回车、换行、空格
*
* @param str
* 被解析字符串
* @return String 解析后的字符串
*/
public static String parse(String str) {
return str.replaceAll("\n", "").replaceAll("chr(13)", "").replaceAll(" ", "");
}
public static Integer[] Str2Integers(String value) {
if (null == value || !org.springframework.util.StringUtils.hasText(value)) {
return null;
}
String[] values = value.split(",");
Integer[] v = new Integer[values.length];
for (int i = 0; i < values.length; i++) {
v[i] = Integer.parseInt(values[i]);
}
return v;
}
public static String[] Str2Strings(String value) {
if (null == value || !org.springframework.util.StringUtils.hasText(value)) {
return null;
}
String[] values = value.split(",");
String[] v = new String[values.length];
for (int i = 0; i < values.length; i++) {
v[i] = values[i];
}
return v;
}
public static int strFormateInt(Object obj) {
if (isNotNull(obj)) {
return "是".equals(obj) ? 1 : 0;
} else {
return 0;
}
}
/**
* 获取UUID
*
* @return UUID
*/
public static String getUUID() {
return (UUID.randomUUID() + "").replaceAll("-", "");
}
/**
* 将字符串转移为ASCII码
*
* @param cnStr
* @return
*/
public static String getCnASCII(String cnStr) {
StringBuffer strBuf = new StringBuffer();
byte[] bGBK = cnStr.getBytes();
for (int i = 0; i < bGBK.length; i++) {
// System.out.println(Integer.toHexString(bGBK[i]&0xff));
strBuf.append(Integer.toHexString(bGBK[i] & 0xff));
}
return strBuf.toString();
}
/**
*
* @param initCode
* 初始化编码
* @param length
* 需要生成编码长度
* @param ind
* 地增量
* @return 递增后的编码
*/
public static String getNextCode(String initCode, int length, int ind) {
Integer temp = Integer.parseInt(initCode);
temp = temp + ind;
String tempCode = temp.toString();
int tempLen = 0;
if (tempCode.length() < length) {
tempLen = length - tempCode.length();
}
for (int i = 0; i < tempLen; i++) {
tempCode = "0" + tempCode;
}
return tempCode;
}
public static int switchNumber(String str) {
char c = str.charAt(0);
int temp = 0;
switch (c) {
// 数值
case '〇':
case '零':
temp = 0;
break;
case '一':
temp = 1;
break;
case '二':
temp = 2;
break;
case '三':
temp = 3;
break;
case '四':
temp = 4;
break;
case '五':
temp = 5;
break;
case '六':
temp = 6;
break;
case '七':
temp = 7;
break;
case '八':
temp = 8;
break;
case '九':
temp = 9;
break;
// 单位,前缀是单数字
case '十':
temp = 10;
break;
}
return temp;
}
/**
* 中文数字转换为阿拉伯数
*
* @param String
* s
*/
public static int cnNumToInt(String s) {
int result = 0;
int yi = 1;// 记录高级单位
int wan = 1;// 记录高级单位
int ge = 1;// 记录单位
char c = s.charAt(0);
int temp = 0;// 记录数值
switch (c) {
// 数值
case '〇':
case '零':
temp = 0;
break;
case '一':
temp = 1 * ge * wan * yi;
ge = 1;
break;
case '二':
temp = 2 * ge * wan * yi;
ge = 1;
break;
case '三':
temp = 3 * ge * wan * yi;
ge = 1;
break;
case '四':
temp = 4 * ge * wan * yi;
ge = 1;
break;
case '五':
temp = 5 * ge * wan * yi;
ge = 1;
break;
case '六':
temp = 6 * ge * wan * yi;
ge = 1;
break;
case '七':
temp = 7 * ge * wan * yi;
ge = 1;
break;
case '八':
temp = 8 * ge * wan * yi;
ge = 1;
break;
case '九':
temp = 9 * ge * wan * yi;
ge = 1;
break;
// 单位,前缀是单数字
case '十':
ge = 10;
break;
case '百':
ge = 100;
break;
case '千':
ge = 1000;
break;
// 高级单位,前缀可以是多个数字
case '万':
wan = 10000;
ge = 1;
break;
case '亿':
yi = 100000000;
wan = 1;
ge = 1;
break;
default:
return -1;
}
result += temp;
if (ge > 1) {
result += 1 * ge * wan * yi;
}
return result;
}
public static String geneStrAry(String str, String splits) {
if (StringUtil.isEmpty(str))
return "";
String[] ary = str.split(splits);
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < ary.length; i++) {
sb.append("'");
sb.append(ary[i]);
sb.append("'");
if (i < ary.length - 1)
sb.append(",");
}
return sb.toString();
}
public static boolean equals(String str1, String str2) {
return str1 == null ? false : str2 == null ? true : str1.equals(str2);
}
public static boolean equalsIgnoreCase(String str1, String str2) {
return str1 == null ? false : str2 == null ? true : str1.equalsIgnoreCase(str2);
}
/**
*
* @param obj
* 传数值类型的obj
* @param format
* @return
*/
public static String decimalFormat(Object obj) {
if (null == obj)
return "";
DecimalFormat df = new DecimalFormat("0.00");
return df.format(obj);
}
/**
*
* @param obj
* 传数值类型的obj
* @param format
* @return
*/
public static String decimalFormat(Object obj, String format) {
if (null == obj)
return "";
DecimalFormat df = new DecimalFormat(format);
return df.format(obj);
}
/**
* 字符串两端增加书名号
*
* @param str
* @return
*/
public static String addBracket(String str) {
if (null == str)
return "";
if (!str.startsWith("《") || !str.endsWith("》")) {
str = "《" + str + "》";
}
return str;
}
/**
* 字符串两端增加书名号,且名称控制在30个字符之内
*
* @param str
* @return
*/
public static String addBracket2Short(String str) {
if (null == str)
return "";
if (!str.startsWith("《") || !str.endsWith("》")) {
str = "《" + (str.length() > 30 ? str.substring(0, 10) + "..." + str.substring(str.length() - 10) : str)
+ "》";
}
return str;
}
/**
* 校验特殊字符
*
* @param productId
* @throws BizException
*/
public static boolean checkCharacter(String str) throws BizException {
if (StringUtil.isEmpty(str)) {
return false;
}
String regEx = "[\\\\\"%/]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
if (m.find()) {
return true;
}
return false;
}
}
package com.pcloud.common.utils.string;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.StringTokenizer;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import com.pcloud.common.exceptions.BizException;
/**
* @描述:字符串工具类
* @作者:DiSeng.H
* @创建时间:2016年3月10日,上午11:49:07 @版本:1.0
*/
public class StringUtil extends StringUtilParent {
/**
* 判断字符串是否为空
*
* @param str
* @return
*/
public static boolean isNotNull(String str) {
if (str != null && !"".equals(str.trim())) {
return true;
} else {
return false;
}
}
/**
* 判断对象是否为空
*
* @param str
* @return
*/
public static boolean isNotNull(Object obj) {
if (obj != null && obj.toString() != null && !"".equals(obj.toString().trim())) {
return true;
} else {
return false;
}
}
/**
* 判断字符串是否为空(自动截取首尾空白)
*
* @param str 源字符串
* @return
*/
public static boolean isEmpty(String str) {
return isEmpty(str, true);
}
/**
* 判断字符串是否为空
*
* @param str 源字符串
* @param trim 是否截取首尾空白
* @return
*/
public static boolean isEmpty(String str, boolean trim) {
return str == null ? true : ("".equals(str.trim()) || "null".equals(str.trim()));
}
/**
* 判断数组是否为空
*
* @param str
* @return
*/
public static boolean isEmpty(String[] strs) {
return strs == null ? true : strs.length == 0;
}
/**
* @param str the string need to be parsed
* @param delim the delimiter to seperate created by zqf at 6/1/2013
*/
@SuppressWarnings({"rawtypes", "unchecked"})
public static String[] parseToArray(String str, String delim) {
ArrayList arr = new ArrayList();
StringTokenizer st = new StringTokenizer(str, delim);
while (st.hasMoreTokens()) {
arr.add(st.nextToken());
}
String[] ret = new String[arr.size()];
for (int i = 0; i < arr.size(); i++) {
ret[i] = (String) arr.get(i);
}
return ret;
}
/**
* replace a old substring with rep in str
*
* @param str the string need to be replaced
* @param old the string need to be removed
* @param rep the string to be inserted
* @return string replaced
*/
public static String replace(String str, String old, String rep) {
if ((str == null) || (old == null) || (rep == null)) {// if one is null
// return ""
return "";
}
int index = str.indexOf(old);
if ((index < 0) || "".equals(old)) { // if no old string found or
// nothing to replace,return the
// origin
return str;
}
StringBuffer strBuf = new StringBuffer(str);
while (index >= 0) { // found old part
strBuf.delete(index, index + old.length());
strBuf.insert(index, rep);
index = strBuf.toString().indexOf(old);
}
return strBuf.toString();
}
/**
* 带逗号分隔的数字转换为NUMBER类型
*
* @param str
* @return
* @throws ParseException
*/
public static Number stringToNumber(String str) throws ParseException {
if (str == null || "".equals(str)) {
return null;
}
DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator('.');
dfs.setGroupingSeparator(',');
dfs.setMonetaryDecimalSeparator('.');
DecimalFormat df = new DecimalFormat("###,###,###,###.##", dfs);
return df.parse(str);
}
public static String getExtensionName(String filename) {
if ((filename != null) && (filename.length() > 0)) {
int dot = filename.lastIndexOf('.');
if ((dot > -1) && (dot < (filename.length() - 1))) {
return filename.substring(dot + 1);
}
}
return filename;
}
/**
* 用于字符串替换
*
* @param target 目标对象 需要替换的字符串
* @param replacement 要替换的字符串
* @param value 替换的值
* @return
*/
public static String replacement(String target, String replacement, String value) {
if (target != null)
return target.replace(replacement, value);
return null;
}
/**
* 判断字符串是否为数字
*
* @param str
* @return
*/
public static boolean isNumeric(String str) {
if (str == null || str.length() == 0) {
return false;
}
for (int i = 0; i < str.length(); i++) {
if (!Character.isDigit(str.charAt(i))) {
return false;
}
}
return true;
}
/**
* 计算指定时间与当前时间的差
*
* @param date
* @return
*/
public static String convDateToString(Date date) {
Long time = new Date().getTime() - date.getTime();
Long min = time / 1000 / 60;
if (min < 5) {
return "刚刚";
} else if (min >= 5 && min < 60) {
return min + "分钟之前";
} else if (min >= 60 && min < 1440) {
return min / 60 + "小时之前";
} else if (min >= 1440 && min < 10080) {
return min / 60 / 24 + "天之前";
} else if (min >= 10080 && min < 40320) {
return min / 60 / 24 / 7 + "周之前";
} else if (min >= 40320 && min < 525600) {
return min / 60 / 24 / 7 / 4 + "月之前";
} else if (min >= 525600) {
return min / 60 / 24 / 365 + "年之前";
}
return null;
}
/**
* @return
* @description 获取当前服务器日期
*/
public static String getCurrdate(String formatStr) {
Calendar cal = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat(formatStr);
String mDateTime = formatter.format(cal.getTime());
return mDateTime;
}
/**
* 将Object值转换成Double类型
*
* @param value
* @return
*/
public static double getDoubleByObj(Object value) {
if (value == null) {
return 0;
}
return Double.valueOf(String.valueOf(value));
}
/**
* 将Object值转换成Float类型
*
* @param value
* @return
*/
public static float getFloatByObj(Object value) {
if (value == null) {
return 0;
}
return Float.valueOf(String.valueOf(value));
}
/**
* 将Object值转换成Integer类型
*
* @param value
* @return
*/
public static Integer getIntegerByObj(Object value) {
if (value == null) {
return 0;
}
return Integer.valueOf(String.valueOf(value));
}
/**
* 将Object值转换成String类型
*
* @param value
* @return
*/
public static String getByObj(Object value) {
if (value == null) {
return null;
}
return value.toString();
}
/**
* 解析字符串 ---> 去掉字符串中回车、换行、空格
*
* @param str 被解析字符串
* @return String 解析后的字符串
*/
public static String parse(String str) {
return str.replaceAll("\n", "").replaceAll("chr(13)", "").replaceAll(" ", "");
}
public static Integer[] Str2Integers(String value) {
if (null == value || !org.springframework.util.StringUtils.hasText(value)) {
return null;
}
String[] values = value.split(",");
Integer[] v = new Integer[values.length];
for (int i = 0; i < values.length; i++) {
v[i] = Integer.parseInt(values[i]);
}
return v;
}
public static String[] Str2Strings(String value) {
if (null == value || !org.springframework.util.StringUtils.hasText(value)) {
return null;
}
String[] values = value.split(",");
String[] v = new String[values.length];
for (int i = 0; i < values.length; i++) {
v[i] = values[i];
}
return v;
}
public static int strFormateInt(Object obj) {
if (isNotNull(obj)) {
return "是".equals(obj) ? 1 : 0;
} else {
return 0;
}
}
/**
* 获取UUID
*
* @return UUID
*/
public static String getUUID() {
return (UUID.randomUUID() + "").replaceAll("-", "");
}
/**
* 将字符串转移为ASCII码
*
* @param cnStr
* @return
*/
public static String getCnASCII(String cnStr) {
StringBuffer strBuf = new StringBuffer();
byte[] bGBK = cnStr.getBytes();
for (int i = 0; i < bGBK.length; i++) {
// System.out.println(Integer.toHexString(bGBK[i]&0xff));
strBuf.append(Integer.toHexString(bGBK[i] & 0xff));
}
return strBuf.toString();
}
/**
* @param initCode 初始化编码
* @param length 需要生成编码长度
* @param ind 地增量
* @return 递增后的编码
*/
public static String getNextCode(String initCode, int length, int ind) {
Integer temp = Integer.parseInt(initCode);
temp = temp + ind;
String tempCode = temp.toString();
int tempLen = 0;
if (tempCode.length() < length) {
tempLen = length - tempCode.length();
}
for (int i = 0; i < tempLen; i++) {
tempCode = "0" + tempCode;
}
return tempCode;
}
public static int switchNumber(String str) {
char c = str.charAt(0);
int temp = 0;
switch (c) {
// 数值
case '〇':
case '零':
temp = 0;
break;
case '一':
temp = 1;
break;
case '二':
temp = 2;
break;
case '三':
temp = 3;
break;
case '四':
temp = 4;
break;
case '五':
temp = 5;
break;
case '六':
temp = 6;
break;
case '七':
temp = 7;
break;
case '八':
temp = 8;
break;
case '九':
temp = 9;
break;
// 单位,前缀是单数字
case '十':
temp = 10;
break;
}
return temp;
}
/**
* 中文数字转换为阿拉伯数
*
* @param String s
*/
public static int cnNumToInt(String s) {
int result = 0;
int yi = 1;// 记录高级单位
int wan = 1;// 记录高级单位
int ge = 1;// 记录单位
char c = s.charAt(0);
int temp = 0;// 记录数值
switch (c) {
// 数值
case '〇':
case '零':
temp = 0;
break;
case '一':
temp = 1 * ge * wan * yi;
ge = 1;
break;
case '二':
temp = 2 * ge * wan * yi;
ge = 1;
break;
case '三':
temp = 3 * ge * wan * yi;
ge = 1;
break;
case '四':
temp = 4 * ge * wan * yi;
ge = 1;
break;
case '五':
temp = 5 * ge * wan * yi;
ge = 1;
break;
case '六':
temp = 6 * ge * wan * yi;
ge = 1;
break;
case '七':
temp = 7 * ge * wan * yi;
ge = 1;
break;
case '八':
temp = 8 * ge * wan * yi;
ge = 1;
break;
case '九':
temp = 9 * ge * wan * yi;
ge = 1;
break;
// 单位,前缀是单数字
case '十':
ge = 10;
break;
case '百':
ge = 100;
break;
case '千':
ge = 1000;
break;
// 高级单位,前缀可以是多个数字
case '万':
wan = 10000;
ge = 1;
break;
case '亿':
yi = 100000000;
wan = 1;
ge = 1;
break;
default:
return -1;
}
result += temp;
if (ge > 1) {
result += 1 * ge * wan * yi;
}
return result;
}
public static String geneStrAry(String str, String splits) {
if (StringUtil.isEmpty(str))
return "";
String[] ary = str.split(splits);
StringBuffer sb = new StringBuffer("");
for (int i = 0; i < ary.length; i++) {
sb.append("'");
sb.append(ary[i]);
sb.append("'");
if (i < ary.length - 1)
sb.append(",");
}
return sb.toString();
}
public static boolean equals(String str1, String str2) {
return str1 == null ? false : str2 == null ? true : str1.equals(str2);
}
public static boolean equalsIgnoreCase(String str1, String str2) {
return str1 == null ? false : str2 == null ? true : str1.equalsIgnoreCase(str2);
}
/**
* @param obj 传数值类型的obj
* @param format
* @return
*/
public static String decimalFormat(Object obj) {
if (null == obj)
return "";
DecimalFormat df = new DecimalFormat("0.00");
return df.format(obj);
}
/**
* @param obj 传数值类型的obj
* @param format
* @return
*/
public static String decimalFormat(Object obj, String format) {
if (null == obj)
return "";
DecimalFormat df = new DecimalFormat(format);
return df.format(obj);
}
/**
* 字符串两端增加书名号
*
* @param str
* @return
*/
public static String addBracket(String str) {
if (null == str)
return "";
if (!str.startsWith("《") || !str.endsWith("》")) {
str = "《" + str + "》";
}
return str;
}
/**
* 字符串两端增加书名号,且名称控制在30个字符之内
*
* @param str
* @return
*/
public static String addBracket2Short(String str) {
if (null == str)
return "";
if (!str.startsWith("《") || !str.endsWith("》")) {
str = "《" + (str.length() > 30 ? str.substring(0, 10) + "..." + str.substring(str.length() - 10) : str)
+ "》";
}
return str;
}
/**
* 校验特殊字符
*
* @param productId
* @throws BizException
*/
public static boolean checkCharacter(String str) throws BizException {
if (StringUtil.isEmpty(str)) {
return false;
}
String regEx = "[\\\\\"%/]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
if (m.find()) {
return true;
}
return false;
}
}
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