可以利用容器的scope="prototype"来保证每一个请求有一个单独的Action来处理,避免struts中Action的线程安全问题。这句话怎么理解呢如果用单例方式会有什么样的结果呢spring 默认scope 是单例模式 这样只会创建一个Action对象 每次访问都是同一个Action对象,数据不安全 struts2 是要求 每次次访问 都对应不同的Action scope="prototype" 可以保证 当有请求的时候 都创建一个Action对象
数据库配置、spring 事务等:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd"
default-lazy-init="true">
<!--PropertyPlaceholderConfigurer这个类,这个类能够把${}内所有配置的变量,根据location配置的Properties合并起来进行替换掉-->
<bean
class="com.xxxxxx.dhm.portalMS.common.util.PortalMSPropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>datasource.properties</value>
</list>
</property>
</bean>
<!--
<jee:jndi-lookup id="dataSource" jndi-name="java:portalMS" /> -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass">
<value>${db.driverclass}</value>
</property>
<property name="jdbcUrl">
<value>${db.jdbcurl}</value>
</property>
<property name="user">
<value>${db.user}</value>
</property>
<property name="password">
<value>${db.password}</value>
</property>
<property name="minPoolSize">
<value>${db.minpoolsize}</value>
</property>
<property name="maxPoolSize">
<value>${db.maxpoolsize}</value>
</property>
<property name="initialPoolSize">
<value>${db.initialpoolsize}</value>
</property>
<property name="maxIdleTime">
<value>${db.maxidletime}</value>
</property>
<property name="acquireIncrement">
<value>${db.acquireincrement}</value>
</property>
<property name="maxStatements">
<value>${db.maxstatements}</value>
</property>
<property name="idleConnectionTestPeriod">
<value>${db.idleconnectiontestperiod}</value>
</property>
<property name="acquireRetryAttempts">
<value>${db.acquireretryattempts}</value>
</property>
<property name="breakAfterAcquireFailure">
<value>${db.breakafteracquirefailure}</value>
</property>
<property name="testConnectionOnCheckout">
<value>${db.testconnectiononcheckout}</value>
</property>
<property name="numHelperThreads">
<value>${db.numhelperthreads}</value>
</property>
<property name="maxStatementsPerConnection">
<value>${db.maxstatementsperconnection}</value>
</property>
<property name="debugUnreturnedConnectionStackTraces">
<value>${db.debugunreturnedconnectionstacktraces}</value>
</property>
<property name="description">
<value>${db.description}</value>
</property>
<property name="checkoutTimeout">
<value>${db.checkouttimeout}</value>
</property>
<property name="autoCommitOnClose">
<value>${db.autocommitonclose}</value>
</property>
<property name="acquireRetryDelay">
<value>${db.acquireretrydelay}</value>
</property>
</bean>
<bean id="sqlMapClient" class="org.springframework.orm.ibatis.SqlMapClientFactoryBean">
<property name="configLocation">
<value>
classpath:ibatis/${dbType}/sqlMapConfig.xml
</value>
</property>
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="dialect" class="com.xxxxxx.dhm.portalMS.base.dialect.${dialect}">
<property name="limit" value="true" />
</bean>
<bean id="sqlExecutor" class="com.xxxxxx.dhm.portalMS.base.executor.LimitSqlExecutor"
scope="prototype">
<property name="dialect" ref="dialect" />
<property name="enableLimit" value="true"></property>
</bean>
<bean id="baseDao" abstract="true"
class="com.xxxxxx.dhm.portalMS.base.dao.ibatis.IbatisDAO" init-method="initialize">
<property name="sqlMapClient">
<ref bean="sqlMapClient" />
</property>
<property name="sqlExecutor">
<ref bean="sqlExecutor" />
</property>
</bean>
<bean id="iBatisTransactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<tx:advice id="txAdvice" transaction-manager="iBatisTransactionManager">
<tx:attributes>
<!-- <tx:method name="del*" propagation="REQUIRED"
rollback-for="com.xxxxxx.dhm.portalMS.exception.portalMSException"></tx:method>
<tx:method name="save*" propagation="REQUIRED"
rollback-for="com.xxxxxx.dhm.portalMS.exception.portalMSException"></tx:method>
<tx:method name="add*" propagation="REQUIRED"
rollback-for="com.xxxxxx.dhm.portalMS.exception.portalMSException"></tx:method>
<tx:method name="update*" propagation="REQUIRED"
rollback-for="com.xxxxxx.dhm.portalMS.exception.portalMSException"></tx:method>
<tx:method name="batch*" propagation="REQUIRED"
rollback-for="com.xxxxxx.dhm.portalMS.exception.portalMSException"></tx:method>
<tx:method name="execute" propagation="REQUIRED"
rollback-for="com.xxxxxx.dhm.portalMS.exception.portalMSException"></tx:method> -->
<tx:method name="*" propagation="REQUIRED" rollback-for="Exception"></tx:method>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="tesConntpoint"
expression="execution(* com.xxxxxx.dhm.portalMS.*.dao..*.*(..)) or execution(* com.xxxxxx.dhm.portalMS.*.service..*.*(..)) " />
<aop:pointcut id="iepgPoint"
expression="execution(* com.xxxxxx.dhm.portalMS.*.service..*.*(..)) or execution(* com.xxxxxx.createPortal.*.service..*.*(..)) or execution(* com.xxxxxx.dhm.common.uif.service.impl.MessageSyncServiceImpl.*(..)) " />
<aop:pointcut id="logpoint"
expression="execution(* com.xxxxxx.dhm.portalMS.*.service..*.*(..))
or execution(* com.xxxxxx.dhm.portalMS.*.dao..*.*(..))" />
<aop:advisor advice-ref="txAdvice" pointcut-ref="iepgPoint" />
<aop:aspect id="logging" ref="logAspect">
<aop:around pointcut-ref="logpoint" method="invoke" />
</aop:aspect>
<aop:aspect id="testConn" ref="testConnAspect">
<aop:before method="before" pointcut-ref="tesConntpoint" />
</aop:aspect>
</aop:config>
<bean id="testConnAspect" class="com.xxxxxx.dhm.portalMS.common.aop.JdbcTestAspect" />
<bean id="logAspect" class="com.xxxxxx.dhm.portalMS.common.aop.LogAspect" />
<bean id="serviceParaCheckInterceptor"
class="com.xxxxxx.miss.util.intercaptor.ServiceParaCheckInterceptor">
</bean>
<bean id="RegexAdvisor"
class="org.springframework.aop.support.RegexpMethodPointcutAdvisor">
<property name="advice">
<ref local="serviceParaCheckInterceptor" />
</property>
<property name="patterns">
<list>
<value>com.xxxxxx.dhm.portalMS.sync.portalms.service.*\.execute</value>
<value>com.xxxxxx.dhm.portalMS.sync.service.*\.execute</value>
<value>com.xxxxxx.dhm.portalMS.sync.action.*\.execute</value>
<value>com.xxxxxx.dhm.portalMS.sync.cms.*\.execute</value>
<value>com.xxxxxx.dhm.portalMS.sync.sme.*\.execute</value>
</list>
</property>
</bean>
<bean id="paraCheckAop"
class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator">
<property name="beanNames">
<list>
<value>SyncColumnServiceImpl</value>
<value>SyncColumnRankServiceImpl</value>
<value>SyncUpShelfRankServiceImpl</value>
<value>DelColumnServiceImpl</value>
<value>SyncColumnImageServiceImpl</value>
<value>DelColumnImageServiceImpl</value>
<value>SyncRelGoodsServiceImpl</value>
<value>DelUpShelfResourceServiceImpl</value>
<value>SyncAllUpShelfResourceServiceImpl</value>
<value>SyncUpShelfResourceServiceImpl</value>
<value>SyncRecommendAssetServiceImpl</value>
<value>DelRecommendAssetServiceImpl</value>
<value>SyncRecommendContentServiceImpl</value>
<value>SyncVirtualNetWorkServiceImpl</value>
<value>DelVirtualNetworkServiceImpl</value>
<value>SyncWidgetServiceImpl</value>
<value>DelWidgetServiceImpl</value>
<value>SyncHotelServiceImpl</value>
<value>DelHotelServiceImpl</value>
<value>CacheModServiceImpl</value>
<value>ModNumServiceImpl</value>
<value>VrecomNumServiceImpl</value>
<value>SyncTemplateStatusServiceImpl</value>
<value>SyncTemplateServiceImpl</value>
<value>DelTemplateServiceImpl</value>
<value>SyncSiteServiceImpl</value>
<value>UpdateSiteStatusServiceImpl</value>
<value>SyncCpServiceImpl</value>
<value>DelCpServiceImpl</value>
<value>AssetTypeAddService</value>
<value>AssetTypeDeleteService</value>
<value>AssetTypeRelationService</value>
<value>ResourcePosterAddAction</value>
<value>ResourcePosterDeleteAction</value>
<value>POResourceAddAction</value>
<value>POResourceDeleteAction</value>
<value>SyncAssetServiceImpl</value>
<value>DelAssetPackageServiceImpl</value>
<value>SyncAssetFileServiceImpl</value>
<value>DelAssetFileServiceImpl</value>
<value>SyncAssetPackageServiceImpl</value>
<value>SyncChannelServiceImpl</value>
<value>DelChannelServiceImpl</value>
<value>SyncChannelTypeServiceImpl</value>
<value>DelChannelTypeServiceImpl</value>
<value>SyncGoodsServiceImpl</value>
<value>SyncGoodsStatusServiceImpl</value>
<value>SyncProdOfferingServiceImpl</value>
<value>SyncProdOfferingStatusServiceImpl</value>
<value>SyncProviderServiceImpl</value>
<value>SyncProviderStatusServiceImpl</value>
<value>SyncUserGroupServiceImpl</value>
<value>DelUserGroupServiceImpl</value>
</list>
</property>
<property name="interceptorNames">
<list>
<value>serviceParaCheckInterceptor</value>
</list>
</property>
</bean>
</beans>
datasource.properties:
db.jdbcurl=jdbc:oracle:thin:@172.20.100.25:1521:orcl
#db.jdbcurl=jdbc:mysql://172.20.100.25:3306/portalms_r004b03
db.user= PORTALMS_R004B03
db.password=coship
db.driverclass=oracle.jdbc.driver.OracleDriver
db.minpoolsize=1
db.maxpoolsize=5
db.initialpoolsize=2
db.maxidletime=120
db.maxstatements=20
db.idleconnectiontestperiod=60
db.acquireretryattempts=30
db.acquireincrement=3
db.breakafteracquirefailure=false
db.maxstatementsperconnection=20
db.numhelperthreads=3
db.testconnectiononcheckout=false
db.acquireretrydelay=1000
db.autocommitonclose=false
db.checkouttimeout=30000
db.description=A pooled c3p0 DataSource
db.debugunreturnedconnectionstacktraces=false
dbType=oracle
dialect=OracleDialect
#dbType=mysql
#dialect = MySQLDialect
package com.XXXXXX.dhm.portalMS.common.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Properties;
import org.springframework.beans.factory.config.PropertyPlaceholderConfigurer;
import org.springframework.core.io.Resource;
import org.springframework.util.DefaultPropertiesPersister;
import org.springframework.util.PropertiesPersister;
import com.XXXXXX.dhm.common.init.SystemInitiator;
public class PortalMSPropertyPlaceholderConfigurer extends PropertyPlaceholderConfigurer
{
private Resource[] locations;
private String fileEncoding;
private boolean ignoreResourceNotFound = false;
private PropertiesPersister propertiesPersister = new DefaultPropertiesPersister();
public void setLocations(Resource[] locations)
{
this.locations = Arrays.copyOf(locations, locations.length);
}
protected void loadProperties(Properties props) throws IOException {
if (this.locations != null) {
for (int i = 0; i < this.locations.length; i++) {
Resource location = this.locations[i];
if (logger.isInfoEnabled()) {
logger.info("Loading properties file from " + location);
}
InputStream is = null;
try {
is = new FileInputStream((SystemInitiator.getSystemInfo()
.getConfPath()
+ File.separator + location.getFilename()));
if (location.getFilename().endsWith(XML_FILE_EXTENSION)) {
this.propertiesPersister.loadFromXml(props, is);
}
else {
if (this.fileEncoding != null) {
this.propertiesPersister.load(props, new InputStreamReader(is, this.fileEncoding));
}
else {
this.propertiesPersister.load(props, is);
}
}
}
catch (IOException ex) {
if (this.ignoreResourceNotFound) {
if (logger.isWarnEnabled()) {
logger.warn("Could not load properties from " + location + ": " + ex.getMessage());
}
}
else {
throw ex;
}
}
finally {
if (is != null) {
is.close();
}
}
}
}
}
public void setFileEncoding(String fileEncoding)
{
this.fileEncoding = fileEncoding;
}
public void setIgnoreResourceNotFound(boolean ignoreResourceNotFound)
{
this.ignoreResourceNotFound = ignoreResourceNotFound;
}
}
package com.xxxxxx.dhm.common.init;
import java.io.PrintStream;
import javax.servlet.ServletContext;
public class SystemInitiator
{
private static SystemInfo systemInfo = null;
public static SystemInfo getSystemInfo()
{
return systemInfo;
}
public static void setSystemInfo(SystemInfo systemInfo)
{
systemInfo = systemInfo;
}
public static void initApp(ServletContext ctx)
{
String FS = System.getProperty("file.separator");
String systemName = ctx.getInitParameter("dhm-system-name");
String work_dir = System.getProperty("user.dir");
String confPath = work_dir + FS + systemName + FS + ctx.getInitParameter("system.config-path-name");
String logPath = work_dir + FS + systemName + FS + ctx.getInitParameter("system.log-path-name");
systemInfo = new SystemInfo(systemName, confPath, logPath);
System.out.println(systemInfo.toString());
}
}
package com.xxxxxx.dhm.common.init;
public class SystemInfo
{
private String systemName = null;
private String confPath = null;
private String logPath = null;
public SystemInfo(String systemName, String confPath, String logPath)
{
this.systemName = systemName;
this.confPath = confPath;
this.logPath = logPath;
}
public String getSystemName()
{
return this.systemName;
}
public String getConfPath()
{
return this.confPath;
}
public String getLogPath()
{
return this.logPath;
}
public String toString()
{
return super.getClass().getName() + "[systemName=" + getSystemName() + ";confPath=" + getConfPath() +
";logPath=" + getLogPath() + "]";
}
}
C3p0PoolConnectionHandler:
package com.XXXXXX.dhm.portalMS.log.poolhandler;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.log4j.jdbcplus.JDBCPoolConnectionHandler;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.mchange.v2.c3p0.ComboPooledDataSource;
public class C3p0PoolConnectionHandler implements JDBCPoolConnectionHandler
{
/**
* 静态的数据源
*/
// private static DataSource dataSource;
private static ComboPooledDataSource dataSource = null;;
private static String configurationFileName = "spring/applicationcontext-datasource.xml";
/**
* 初始化数据源
*/
static
{
initDataSource();
}
/**
* 初始化数据源
*/
private static void initDataSource()
{
try
{
if (null == dataSource)
{
ApplicationContext applicationContext = new ClassPathXmlApplicationContext(
configurationFileName);
dataSource = (ComboPooledDataSource) applicationContext.getBean("dataSource");
}
}
catch (Exception ex)
{
ex.printStackTrace();
}
}
/**
* 获得数据库连接
* @return Connection 数据库连接
*/
public Connection getConnection()
{
Connection conn = null;
try
{
if (dataSource == null)
{
initDataSource();
}
conn = dataSource.getConnection();
}
catch (SQLException exception)
{
System.err.println("Could not get connection.");
exception.printStackTrace();
}
return conn;
}
/**
* 获得数据库连接
* @param _url 数据库连接字符串
* @param _username 数据库用户名
* @param _password 数据库密码
* @return Connection 数据库连接
*/
public Connection getConnection(String _url, String _username,
String _password)
{
return getConnection();
}
/**
* 释放数据库连接,回调方法
* @param con 数据库连接
* @throws Exception 向外抛出异常
*/
public void freeConnection(Connection con) throws Exception
{
con.close();
}
}
IbatisDAO:
/*
* 工 程 名: portalMS
* 包 名: com.XXXXXX.dhm.portalMS.base.dao.ibatis
* 文 件 名: IbatisDAO.java
* 版 权: Copyright (c) 2009 XXXXXX All Rights Reserved.
* 描 述: 通过ibatis底层实现具体的操作,抽象类
*/
package com.XXXXXX.dhm.portalMS.base.dao.ibatis;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;
import java.util.Map;
import org.springframework.dao.DataAccessException;
import org.springframework.orm.ibatis.support.SqlMapClientDaoSupport;
import com.XXXXXX.dhm.portalMS.base.dao.IIbatisDAO;
import com.XXXXXX.dhm.portalMS.base.executor.LimitSqlExecutor;
import com.XXXXXX.dhm.portalMS.common.Constants;
import com.XXXXXX.dhm.portalMS.common.util.PageList;
import com.XXXXXX.dhm.portalMS.common.util.ReflectUtil;
import com.XXXXXX.dhm.portalMS.exception.PortalMSException;
import com.ibatis.sqlmap.engine.execution.SqlExecutor;
import com.ibatis.sqlmap.engine.impl.SqlMapClientImpl;
import com.ibatis.sqlmap.engine.impl.SqlMapExecutorDelegate;
/**
*
* IIbatisDAO 类的抽象实现, 部分实现公共的增删改查功能,子类可以继续扩展该类的方法
*/
public abstract class IbatisDAO<T extends Serializable, PK extends Serializable> extends SqlMapClientDaoSupport
implements IIbatisDAO<T, PK>
{
/**
* 序列化的ID
*/
private static final long serialVersionUID = 7489415169618169154L;
/**
* ibatis中sqlmap命名空间
*/
private String nameSpace = "";
/**
* 实体类
*/
private Class<T> entityClass;
/**
* SQL语句的操作对象
*/
protected SqlExecutor sqlExecutor;
/**
* 对命名空间进行了赋值,可以通过命名空间执行具体的sqlMap对应的语句 <默认构造函数>
*/
@SuppressWarnings("unchecked")
public IbatisDAO()
{
this.entityClass = null;
Class c = getClass();
// 得到具体的子类类型
Type t = c.getGenericSuperclass();
if (t instanceof ParameterizedType)
{
Type[] p = ((ParameterizedType) t).getActualTypeArguments();
this.entityClass = (Class<T>) p[0];
// 得到命名空间,用于向sqlMap传入
nameSpace = entityClass.getSimpleName() + ".";
}
}
/**
* 对SQL语句操作对象进行赋值
*
* @param sqlExecutor
*/
public void setSqlExecutor(SqlExecutor sqlExecutor)
{
this.sqlExecutor = sqlExecutor;
}
/**
* 对是否支持物理分页进行赋值 spring注入方法,注入具体的sqlExecutor是否支持物理分页
*
* @param enableLimit
* [是否支持物理分页,true-支持,false-不支持]
* @see LimitSqlExecutor#setEnableLimit(boolean)
*/
public void setEnableLimit(boolean enableLimit)
{
if (sqlExecutor instanceof LimitSqlExecutor)
{
((LimitSqlExecutor) sqlExecutor).setEnableLimit(enableLimit);
}
}
/**
* 初始化sqlExcutor类,在spring初始化时会加载该方法
* 因为ibatis本身不支持物理分页,用自己定义的sqlExecutor来替代默认的sqlExecutor
*
* @exception throws [Exception] [向上层直接抛出]
* @see SqlMapExecutorDelegate
*/
public void initialize() throws Exception
{
if (sqlExecutor != null)
{
SqlMapClientImpl client = (SqlMapClientImpl) getSqlMapClient();
SqlMapExecutorDelegate delgate = client.getDelegate();
// 由于SqlMapExecutorDelegate没有setSqlExecutor方法,利用反射强行对sqlExecutor赋值
ReflectUtil.setFieldValue(delgate, "sqlExecutor", SqlExecutor.class, sqlExecutor);
}
}
/**
* 按主键删除实体对象
*
* @param id
* 泛型主键ID
* @throws PortalMSException
*/
public void deleteByKey(PK id) throws PortalMSException
{
try
{
getSqlMapClientTemplate().delete(nameSpace + SQLID_DELETE, id);
}
catch (Exception ex)
{
throw new PortalMSException(Constants.ERROR_CODE_OPERATOR_DATABASE.getLongValue(), ex);
}
}
@SuppressWarnings("unchecked")
/**
* 查找符合条件的所有对象
* @return List,List中存放泛型的实体对象
*/
public List<T> findAll() throws PortalMSException
{
try
{
return getSqlMapClientTemplate().queryForList(nameSpace + SQLID_FINDALL);
}
catch (Exception ex)
{
throw new PortalMSException(Constants.ERROR_CODE_OPERATOR_DATABASE.getLongValue(), ex);
}
}
@SuppressWarnings("unchecked")
/**
* 按主键查找实体对象
* @param id 泛型主键
* @return 泛型实体,实现序列化接口的任何类型
* @throws portalMSException
*/
public T findById(PK id) throws PortalMSException
{
T result = null;
try
{
result = (T) this.getSqlMapClient().queryForObject(nameSpace + SQLID_FINDBYID, id);
}
catch (Exception e)
{
throw new PortalMSException(Constants.ERROR_CODE_ACCESS_DATABASE.getLongValue(), e);
}
return result;
}
/**
* 保存实体对象,数据库的insert操作
*
* @param entity
* 参数类型:泛型,任何实现序列化的类
* @throws PortalMSException
* iepg管理系统统一抛出的异常
*/
public void saveEntity(T entity) throws PortalMSException
{
try
{
this.getSqlMapClient().insert(nameSpace + SQLID_INSERT, entity);
}
catch (Exception e)
{
throw new PortalMSException(Constants.ERROR_CODE_OPERATOR_DATABASE.getLongValue(), e);
}
}
/**
* 更新实体对象,数据库的update操作
*
* @param entity
* 参数类型:泛型,任何实现序列化的类
* @throws PortalMSException
* iepg管理系统统一抛出的异常
*/
public void updateEntity(T entity) throws PortalMSException
{
try
{
this.getSqlMapClient().update(nameSpace + SQLID_UPDATE, entity);
}
catch (Exception e)
{
throw new PortalMSException(Constants.ERROR_CODE_OPERATOR_DATABASE.getLongValue(), e);
}
}
/**
* 按实体对象的主键ID批量删除实体 空方法,子类需要时自己去实现
*
* @param list
* 主键的ID列表,列表内存放泛型,任何实现序列化接口的类
*/
public void batchDelete(final List<PK> list) throws PortalMSException
{
}
/**
* 按实体对象的主键ID批量删除实体 空方法,子类需要时自己去实现
*
* @param args
* 主键的ID列表,列表内存放泛型,任何实现序列化接口的类
*/
public void batchDelete(final PK[] args) throws PortalMSException
{
}
/**
* 批量插入实体,数据库insert操作 空方法,子类需要使用时自己去实现
*
* @param list
* 实体对象列表,列表内存放泛型,任何实现序列化接口的类
*/
public void batchInsert(final List<T> list) throws PortalMSException
{
}
/**
* 批量更新实体,数据库update操作 空方法,子类需要使用时自己去实现
*
* @param list
* 实体对象列表,列表内存放泛型,任何实现序列化接口的类
*/
public void batchUpdate(final List<T> list) throws PortalMSException
{
}
/**
* 按查询条件分页查询记录数
* @param map 查询的参数,封装为map或一个实体对象
* @param currPage 当前的页码
* @param pageSize 每页显示的记录数
* @return List 实体对象的列表
* @throws IEMPMException
*/
@SuppressWarnings("unchecked")
public List<T> findByCriteria(Object map, String sqlMap, int currPage, int pageSize) throws PortalMSException
{
// 举例:当前页为第2页,每页显示10条,则开始记录数为11,结束记录数为20
// 得到记录的开始数
int skipResults = (currPage - 1) * pageSize + 1;
// 得到记录的结束数
int maxResults = currPage * pageSize;
Map<String, Object> obj = null;
int totalRows = 0;
// 判断是否map类型,还是普通的JavaBean。普通的JavaBean则转换成Map类型
if (map instanceof Map)
{
obj = (Map) map;
}
else
{
obj = ReflectUtil.getObjectAsMap(map);
}
// obj.put("siteID", SessionUtil.getLocalSiteID());
try
{
totalRows = this.getRowCount(obj, sqlMap);
}
catch (Exception e)
{
throw new PortalMSException(Constants.ERROR_CODE_OPERATOR_DATABASE.getLongValue(), e);
}
// 带分页参数的列表
PageList<T> pageList = new PageList<T>(currPage, pageSize, totalRows);
// 支持物理分页页码从1开始
try
{
List queryResult = this.getSqlMapClientTemplate().queryForList(sqlMap, obj, skipResults, maxResults);
if (queryResult != null)
{
pageList.addAll(queryResult);
}
}
catch (Exception e)
{
throw new PortalMSException(Constants.ERROR_CODE_ACCESS_DATABASE.getLongValue(), e);
}
return pageList;
}
@SuppressWarnings("unchecked")
/**
* 按查询条件返回所有记录,不带分页
* @param map 查询的参数,封装为map或一个实体对象
* @return List 实体对象的列表
*/
public List<T> findByCriteria(Object map) throws PortalMSException
{
Map<String, Object> obj = null;
// 判断是否map类型,还是普通的JavaBean。普通的JavaBean则转换成Map类型
if (map instanceof Map)
{
obj = (Map) map;
}
else
{
obj = ReflectUtil.getObjectAsMap(map);
}
// obj.put("siteID", SessionUtil.getLocalSiteID());
List<T> resultList = null;
try
{
resultList = getSqlMapClientTemplate().queryForList(nameSpace + SQLID_FINDALL, obj);
}
catch (Exception e)
{
throw new PortalMSException(Constants.ERROR_CODE_ACCESS_DATABASE.getLongValue(), e);
}
return resultList;
}
/**
* 按查询条件得到该SQL语句的总数量
*
* @param map
* 查询条件
* @return Integer 记录总数
* @throws DataAccessException
* 数据访问异常
*/
@SuppressWarnings("unchecked")
public Integer getRowCount(Object map) throws PortalMSException
{
try
{
Map<String, Object> obj = null;
// 判断是否map类型,还是普通的JavaBean。普通的JavaBean则转换成Map类型
if (map instanceof Map)
{
obj = (Map) map;
}
else
{
obj = ReflectUtil.getObjectAsMap(map);
}
// obj.put("siteID", SessionUtil.getLocalSiteID());
return (Integer) this.getSqlMapClientTemplate().queryForObject(nameSpace + SQLID_ROWCOUNT, obj);
}
catch (Exception ex)
{
throw new PortalMSException(Constants.ERROR_CODE_ACCESS_DATABASE.getLongValue(), ex);
}
}
/**
* 按查询条件得到该SQL语句的总数量
*
* @param map
* 查询条件
*
* @param sqlMap
* SQL查询语句
*
* @return Integer 记录总数
* @throws DataAccessException
* 数据访问异常
*/
@SuppressWarnings("unchecked")
public Integer getRowCount(Object map, String sqlMap) throws PortalMSException
{
try
{
Map<String, Object> obj = null;
// 判断是否map类型,还是普通的JavaBean。普通的JavaBean则转换成Map类型
if (map instanceof Map)
{
obj = (Map) map;
}
else
{
obj = ReflectUtil.getObjectAsMap(map);
}
// obj.put("siteID", SessionUtil.getLocalSiteID());
return (Integer) this.getSqlMapClientTemplate().queryForObject(sqlMap + "." + SQLID_ROWCOUNT, obj);
}
catch (Exception ex)
{
throw new PortalMSException(Constants.ERROR_CODE_ACCESS_DATABASE.getLongValue(), ex);
}
}
/**
* 得到查询结果集的行数,此参数用于分页
*
* @return Integer记录集的行数
* @throws PortalMSException
*/
public Integer getRowCount() throws PortalMSException
{
try
{
return (Integer) this.getSqlMapClientTemplate().queryForObject(nameSpace + SQLID_ROWCOUNT);
}
catch (Exception ex)
{
throw new PortalMSException(Constants.ERROR_CODE_ACCESS_DATABASE.getLongValue(), ex);
}
}
@SuppressWarnings("unchecked")
/**
* 按查询条件分页查询记录数
* @param map 查询的参数,封装为map或一个实体对象
* @param currPage 当前的页码
* @param pageSize 每页显示的记录数
* @return List 实体对象的列表
* @throws IEMPMException
*/
public List<T> findByCriteria(Object map, int currPage, int pageSize) throws PortalMSException
{
// 举例:当前页为第2页,每页显示10条,则开始记录数为11,结束记录数为20
// 得到记录的开始数
int skipResults = (currPage - 1) * pageSize + 1;
// 得到记录的结束数
int maxResults = currPage * pageSize;
Map<String, Object> obj = null;
int totalRows = 0;
// 判断是否map类型,还是普通的JavaBean。普通的JavaBean则转换成Map类型
if (map instanceof Map)
{
obj = (Map) map;
}
else
{
obj = ReflectUtil.getObjectAsMap(map);
}
// obj.put("siteID", SessionUtil.getLocalSiteID());
try
{
totalRows = this.getRowCount(obj);
}
catch (Exception e)
{
throw new PortalMSException(Constants.ERROR_CODE_OPERATOR_DATABASE.getLongValue(), e);
}
// 带分页参数的列表
PageList<T> pageList = new PageList<T>(currPage, pageSize, totalRows);
// 支持物理分页页码从1开始
try
{
List queryResult = this.getSqlMapClientTemplate().queryForList(nameSpace + SQLID_FINDALL, obj, skipResults,
maxResults);
if (queryResult != null)
{
pageList.addAll(queryResult);
}
}
catch (Exception e)
{
throw new PortalMSException(Constants.ERROR_CODE_ACCESS_DATABASE.getLongValue(), e);
}
return pageList;
}
/**
* * 按查询条件分页查询记录数
* @param map 查询的参数,封装为map或一个实体对象
* @param currPage 当前的页码
* @param pageSize 每页显示的记录数
* @return List 实体对象的列表
* @throws IEMPMException
*/
@SuppressWarnings("unchecked")
public PageList<T> findByCriteria(Object map, String sqlname,
String countSqlName, int currPage, int pageSize)
throws PortalMSException
{
// 举例:当前页为第2页,每页显示10条,则开始记录数为11,结束记录数为20
// 取得配置文件是MySQL还是Oracle数据库
int skipResults = (currPage - 1) * pageSize + 1;
// 得到记录的结束数
int maxResults = currPage * pageSize;
Map<String, Object> obj = null;
int totalRows = 0;
// 判断是否map类型,还是普通的JavaBean。普通的JavaBean则转换成Map类型
if (map instanceof Map)
{
obj = (Map) map;
}
else
{
obj = ReflectUtil.getObjectAsMap(map);
}
// obj.put("siteID", SessionUtil.getLocalSiteID());
PageList<T> pageList;
try
{
totalRows = (Integer) this.getSqlMapClientTemplate().queryForObject(countSqlName, obj);
// 带分页参数的列表
pageList = new PageList<T>(currPage, pageSize, totalRows);
// 支持物理分页页码从1开始
List queryResult = this.getSqlMapClientTemplate().queryForList(
sqlname, obj, skipResults, maxResults);
if (queryResult != null)
{
pageList.addAll(queryResult);
}
}
catch (Exception e)
{
throw new PortalMSException(Constants.ERROR_CODE_OPERATOR_DATABASE
.getStringValue(), e);
}
return pageList;
}
}
ServiceParaCheckInterceptor:
package com.XXXXXX.miss.util.intercaptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.apache.log4j.Logger;
import com.XXXXXX.dhm.aaa.commons.constant.CommonConst;
import com.XXXXXX.dhm.aaa.commons.constant.SerErrorCommonCode;
import com.XXXXXX.dhm.aaa.commons.util.StringUtil;
import com.XXXXXX.miss.util.config.CheckField;
import com.XXXXXX.miss.util.config.CheckRulerConfig;
import com.XXXXXX.miss.util.config.FieldRuler;
import com.XXXXXX.miss.util.config.InterRulerConfig;
import com.XXXXXX.miss.util.config.JoinFiledRuler;
import com.XXXXXX.miss.util.config.SerFactory;
import com.XXXXXX.dhm.common.config.impl.PropertiesFactory;
import com.XXXXXX.dhm.common.uif.vo.IRequestMessageBody;
import com.XXXXXX.dhm.common.uif.vo.MessageBody;
import com.XXXXXX.dhm.common.uif.vo.ReturnMessage;
import com.XXXXXX.dhm.common.uif.vo.cms.CMSMessage;
import com.XXXXXX.dhm.common.uif.vo.cms.cms2iepg.body.IepgAssetRequestBody;
/**
* 参数较验拦截器 ServiceParaCheckInterceptor.java
* <p>
* Copyright: Copyright (c) 2009
* <p>
* <p>
* Company: XXXXXX
* </p>
*/
public class ServiceParaCheckInterceptor implements MethodInterceptor
{
private final static Logger log = Logger.getLogger(ServiceParaCheckInterceptor.class);
@SuppressWarnings("unchecked")
public Object invoke(MethodInvocation invocation) throws Throwable
{
try
{
// 取出被拦截方法的参数集
Object[] args = invocation.getArguments();
Object o = null;
if (args[0] instanceof IRequestMessageBody)
{
IRequestMessageBody dr = (IRequestMessageBody) args[0];
// 取出要校验的对象
o = dr.getReqMsg();
}
else if (args[0] instanceof MessageBody)
{
o = args[0];
}
// if (o == null && args[0] instanceof IepgAssetRequestBody)
// {
// IepgAssetRequestBody dr = (IepgAssetRequestBody) args[0];
// o = dr.getResourcePackage();
// if(o == null)
// {
// o= dr.getPackageCode();
// }
// if(o == null)
// {
// o= dr.getIepgAssetMessage();
// }
// }
else
{// 对象格式有误
log.error(" object format error ");
ReturnMessage rm = new ReturnMessage();
rm.setReturnCode(SerErrorCommonCode.UNKNOWN_ERROR);
return rm;
}
Class c = o.getClass();
// 取出接口参数的字段集
Field[] fa = c.getDeclaredFields();
// 由接口ID取出此接口对应的InterRulerConfig对象
CheckRulerConfig crc = SerFactory.getCheckConfig();
// 取出接口规则Map
Map<String, InterRulerConfig> iRuleMap = crc.getIRuleMap();
// 取出被拦截的类名
Class clazz = invocation.getThis().getClass();
String rulerName = clazz.getSimpleName();
String interID = CommonConst.INTER_RULER_PREFIX + rulerName;
// 由接口ID取出接口的校验规则
InterRulerConfig ir = iRuleMap.get(interID);
// 如果此接口没有定义校验规则,则不对此接口进行校验
if (ir == null)
{
return invocation.proceed();
}
// 如果此接口规则引用其他接口的规则进行校验,就取出引用的接口规则
if (!ir.getRef().equals(""))
{
ir = iRuleMap.get(ir.getRef());
}
// 取出字段校验规则的map
Map<String, FieldRuler> rulerMap = ir.getFRuleMap();
for (int i = 0; i < fa.length; i++)
{
// 取校验规则
FieldRuler fr = rulerMap.get(fa[i].getName().toLowerCase());
// 如果此字段没有给出校验规则,则不对此字段进行校验
if (fr == null)
{
continue;
}
Method method = c.getMethod(getMethodName(fa[i].getName()), new Class[0]);
Object fo = method.invoke(o, new Object[0]);// get方法无参\
// 类里的属性是否为ArrayList类型
if (fr.getType() != null && fr.getType().equals("list") && null != fo)
{
List tempList = (ArrayList) fo;
// 验证List下的元素属性
for (int temp = 0; temp < tempList.size(); temp++)
{
ReturnMessage validataResult = validataChildFiled(tempList.get(temp), rulerMap, o);
// 验证失败
if (!SerErrorCommonCode.SUCCEED.equals(validataResult.getReturnCode()))
{
return validataResult;
}
}
}
// 验证属性
ReturnMessage rm = checkField(fa[i].getName().toLowerCase(), rulerMap, fo, o);
if (!SerErrorCommonCode.SUCCEED.equals(rm.getReturnCode()))
{
return rm;
}
}
}
catch (Exception e)
{
log.error("parameter check failed!", e);
ReturnMessage rm = new ReturnMessage();
rm.setReturnCode(SerErrorCommonCode.PARA_CHECK_FAILED);
rm.setErrorMessage(PropertiesFactory.getValueString(SerErrorCommonCode.PARA_CHECK_FAILED));
return rm;
}
// 如果参数校验通过,则调用被拦截的方法
return invocation.proceed();
}
/**
* 根据校验规则对属性值进行检查
*
* @param lowerCaseValue
* @param rulerMap
* @param fo
* @return
* @throws NoSuchMethodException
* @throws SecurityException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
private ReturnMessage checkField(String lowerCaseValue, Map<String, FieldRuler> rulerMap, Object fo, Object o)
throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
ReturnMessage rm = new ReturnMessage();
rm.setReturnCode(SerErrorCommonCode.SUCCEED);
FieldRuler fr = rulerMap.get(lowerCaseValue);
// 如果此字段没有给出校验规则,则不对此字段进行校验
if (fr == null)
{
return rm;
}
// 如果要校验的字段值为空,而校验规则规定其是必选项,则返回校验失败
if (fo == null || fo.toString().equals(""))
{
if (fr.getNeed().equalsIgnoreCase(CommonConst.YES))
{
rm.setReturnCode(SerErrorCommonCode.PARA_CHECK_FAILED);
rm.setErrorMessage(PropertiesFactory.getValueString(SerErrorCommonCode.PARA_CHECK_FAILED)
+ CommonConst.ERROR_DESC + fr.getId());
return rm;
}
else
{
return rm;
}
}
rm = null;
return this.checkValidate(fr, fo, o);
}
/**
* 迭代验证ArrayList元素属性
*
* @param object
* @param rulerMap
* @return
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
@SuppressWarnings("unchecked")
private ReturnMessage validataChildFiled(Object object, Map<String, FieldRuler> rulerMap, Object o)
throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
ReturnMessage rm = new ReturnMessage();
rm.setReturnCode(SerErrorCommonCode.SUCCEED);
Object tempObj = object;
Field[] fields = object.getClass().getDeclaredFields();
for (int i = 0; i < fields.length; i++)
{
// 取校验规则
FieldRuler fr = rulerMap.get(fields[i].getName().toLowerCase());
// 如果此字段没有给出校验规则,则不对此字段进行校验
if (fr == null)
{
continue;
}
Method method = object.getClass().getMethod(getMethodName(fields[i].getName()), new Class[0]);
// 通过get方法,获取属性值
Object fo = method.invoke(tempObj, new Object[0]);
// 如果子元素属性是集合类型,则继续验证集合中的数据
if (fr.getType() != null && fr.getType().equals("list") && null != fo)
{
List tempList = (ArrayList) fo;
object = null;
tempObj = null;
// 递归进行验证
for (int temp = 0; temp < tempList.size(); temp++)
{
rm = null;
validataChildFiled(tempList.get(temp), rulerMap, tempObj);
}
}
// 验证属性
rm = checkField(fields[i].getName().toLowerCase(), rulerMap, fo, tempObj);
if (!SerErrorCommonCode.SUCCEED.equals(rm.getReturnCode()))
{
return rm;
}
}
return rm;
}
/**
* 对特定字段的值进行校验
*
* @param fr
* @param value
* @return
* @throws NoSuchMethodException
* @throws SecurityException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws IllegalArgumentException
*/
@SuppressWarnings("unchecked")
private ReturnMessage checkValidate(FieldRuler fr, Object value, Object o) throws SecurityException,
NoSuchMethodException, IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
ReturnMessage rm = new ReturnMessage();
if (fr.getType() != null && fr.getType().equals("list") && null != value)
{
List tempList = (ArrayList) value;
if (tempList.isEmpty() && fr.getNeed().equals("yes"))
{
rm.setReturnCode(SerErrorCommonCode.PARA_CHECK_FAILED);
rm.setErrorMessage(PropertiesFactory.getValueString(SerErrorCommonCode.PARA_CHECK_FAILED)
+ " ,field name is :" + fr.getId());
}
else
{
rm.setReturnCode(SerErrorCommonCode.SUCCEED);
}
return rm;
}
Pattern p = Pattern.compile(fr.getRegex());
Matcher m = p.matcher(value.toString());
// 规则校验 长度校验
if (!m.matches() || !validateDBAllowMaxLength(fr.getMaxLength(), value.toString()))
{
rm.setReturnCode(SerErrorCommonCode.PARA_CHECK_FAILED);
rm.setErrorMessage(PropertiesFactory.getValueString(SerErrorCommonCode.PARA_CHECK_FAILED)
+ " ,filed name is :" + fr.getId());
return rm;
}
return validataJoinFiledRuler(rm, fr, value, o);
}
/**
* 级联校验
* 举例说明:
* <field id="ProdOfferingCode" regex="^\w{1,20}$" need="yes">
* <joinCheck>
* <attribute value="1" >
* <checkFile refField="region" regex="^\w{1,20}$"/>
* </attribute>
* </joinCheck>
* 当ProdOfferingCode的值为1时, region的值必须满足regex 的校验规则
*
* @param rm
* @param fr
* @param value
* @param o
* @throws SecurityException
* @throws NoSuchMethodException
* @throws IllegalArgumentException
* @throws IllegalAccessException
* @throws InvocationTargetException
*/
@SuppressWarnings("unchecked")
private ReturnMessage validataJoinFiledRuler(ReturnMessage rm, FieldRuler fr, Object value, Object o)
throws SecurityException, NoSuchMethodException, IllegalArgumentException, IllegalAccessException,
InvocationTargetException
{
// 默认返回成功
rm.setReturnCode(SerErrorCommonCode.SUCCEED);
// 级联校验(基于本属性对其他属性进行校验)
if (fr.getJoinCheckFiled() == null)
{
return rm;
}
Map<String, CheckField> checkMAp = fr.getJoinCheckFiled().getJoinCheck();
if (checkMAp == null || !checkMAp.containsKey(value))
{
return rm;
}
JoinFiledRuler joinFiledRuler = fr.getJoinCheckFiled();
Map<String, CheckField> map = joinFiledRuler.getJoinCheck();
CheckField checkField = map.get(value);
Class c = o.getClass();
Method method = c.getMethod(getMethodName(checkField.getRefField()), new Class[0]);
Object fo = method.invoke(o, new Object[0]);// get方法无参\
String checkStr = "";
if (fo != null)
{
checkStr =fo.toString();
}
Pattern p = Pattern.compile(checkField.getRegex());
Matcher m = p.matcher(checkStr);
// 规则校验 长度校验
if (!m.matches() || !validateDBAllowMaxLength(checkField.getMaxLength(), checkStr))
{
rm.setReturnCode(SerErrorCommonCode.PARA_CHECK_FAILED);
rm.setErrorMessage(PropertiesFactory.getValueString(SerErrorCommonCode.PARA_CHECK_FAILED)
+ " ,filed name is :" + checkField.getRefField());
}
return rm;
}
/**
* 验证DB允许的长度值
*
* @param length
* @param value
* @return
*/
private boolean validateDBAllowMaxLength(String length, String value)
{
// length为null,则不需要验证
if (null == length)
{
return true;
}
// 值的长度大于DB允许的长度时
if (Integer.parseInt(length) < StringUtil.getLengthInOracle(value))
{
return false;
}
return true;
}
public static String getMethodName(String name)
{
return "get" + firstLetterToUpperCase(name);
}
/**
* 首字母小写变大写
*/
public static String firstLetterToUpperCase(String name)
{
if (name == null || name.length() == 0)
{
return name;
}
char[] chars = name.toCharArray();
chars[0] = Character.toUpperCase(chars[0]);
return new String(chars);
}
}
public class CommonConst
{
public static final String SEPARATOR = ";";
public static final String JAVA_RMI_SERVER_HOSTNAME = "dhm.aaa.cluster.rmi_hostname";
public static final String SHELL_DISK_USAGE_PATH = "dhm.aaa.shellPath.getDiskUsagePath";
public static final String SHELL_CURRENT_SYS_DISK_USAGE_PATH = "dhm.aaa.shellPath.currentSysDisk";
public static final String SHELL_CPU_USAGE_PATH = "dhm.aaa.shellPath.getCpuUsagePath";
public static final String CONN_DCC_OVER_TIME = "connDcssConfig.connOverTime";
public static final String CONN_DCC_HEART_OVER_TIME = "connDcssConfig.connOutTime";
public static final String CONN_DCC_GRANT_FAIL_INTERVAL = "connDcssConfig.grantFailInterval";
public static final String CONN_DCC_GRANT_WARN_TIME = "connDcssConfig.grantWarnTime";
public static final String CONN_DCC_TEST_KEY = "connDcssConfig.connDccKey";
public static final String CONN_DCC_TEST_TYPE = "connDcssConfig.connDccType";
public static final String BOSS_FLAG = "dhm.aaa.service.bossConfig.bossFlag";
public static final String HJ_BOSS_CONFIG_PATH = "dhm.aaa.service.bossConfig.hj_configPath";
public static final String DWT_BOSS_CONFIG_PATH = "dhm.aaa.service.bossConfig.dwt_configPath";
public static final int DWT_BOSS_FLAG = 2;
public static final int HJ_BOSS_FLAG = 1;
public static final String INTER_RULER_PREFIX = "interRuler.";
public static final String YES = "yes";
public static final String ERROR_DESC = " ,field name is :";
public static final String START_INDEX = "StartIndex";
public static final String END_INDEX = "EndIndex";
public static final String HHMMSS_REGEXP = "^([0-1][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$";
}
public class SerErrorCommonCode
{
public static final String SUCCEED = "0";
public static final String UNKNOWN_ERROR = "500";
public static final String INUALID_XML = "1001";
public static final String PARAM_VERSION_NULL = "1002";
public static final String TRANSACTIONID_IS_NULL = "1003";
public static final String TIMESTAMP_IS_NULL = "1004";
public static final String TRANSACTIONID_EXIST = "1005";
public static final String UNLAWFUL_CHAR = "1006";
public static final String PARA_CHECK_FAILED = "1007";
public static final String UNLAWFUL_INTERZONE = "1008";
public static final String DATE_FORMAT_ERROR = "1009";
public static final String NUMBER_FORMAT_ERROR = "1010";
public static final String DATA_CONNECTION_FIAL = "1011";
public static final String DATA_CONNECTION_ERROR = "1012";
public static final String NULAWFUL_MSGSRC = "1013";
public static final String DISK_CALL_ERROR = "1014";
public static final String NETWORK_CALL_ERROR = "1015";
public static final String NET_CALL_ERROR = "1016";
public static final String AUTHENTICATION_MAX_ERROR = "1017";
public static final String ONLINE_MAX_ERROR = "1018";
}
public class SerStateCode
{
public static final String PLATFORM_CODE_DHM = "0";
public static final String PLATFORM_CODE_WIDGET = "1";
public static final String DOC_USER_TYPE_A = "A";
public static final String DOC_USER_TYPE_C = "C";
public static final String DOC_USER_TYPE_S = "S";
public static final String PARENT_REGION_ID = "0";
public static final int PRODUCT_UNAVAILABLE = 0;
public static final int PRODUCT_AVAILABLE = 1;
public static final String DOC_RESOURCE_NORMAL_STATUS = "1";
public static final String DOC_RESOURCE_DOWN_LINE = "3";
public static final String DB_RESOURCE_NORMAL_STATUS = "0";
public static final String DB_RESOURCE_CANCEL_STATUS = "1";
public static final String DB_BILLING_STATUS_NATURAL = "0";
public static final String DB_BILLING_STATUS_ARREAR = "1";
public static final String DB_BILLING_PAYTYPE_REALTIME = "01";
public static final String DB_BILLING_PAYTYPE_PRESELLFEE = "02";
public static final String PRICE_POLICY_CHARGE_TERM_UNIT_MINUTE = "0";
public static final String PRICE_POLICY_CHARGE_TERM_UNIT_HOUR = "1";
public static final String PRICE_POLICY_CHARGE_TERM_UNIT_DAY = "2";
public static final String PRICE_POLICY_CHARGE_TERM_UNIT_MONTH = "3";
public static final String PRICE_POLICY_CHARGE_TERM_UNIT_YEAR = "4";
public static final String PRICE_POLICY_CHARGE_TERM_UNIT_FREE = "5";
public static final String PRICE_POLICY_CHARGE_TERM_UNIT_A = "6";
public static final String PRICE_POLICY_CHARGE_TERM_UNIT_TIMES = "7";
public static final String PRICE_POLICY_CHARGE_TERM_UNIT_TIME = "8";
public static final int MONTH_DAY = 30;
public static final String DOC_LOGICTYPE_AND = "0";
public static final String DOC_LOGICTYPE_OR = "1";
public static final String QUERY_USER_NOW_SUBCSCRIPTION = "0";
public static final String QUERY_USER_HISTORY_SUBCSCRIPTION = "1";
public static final String QUERY_SUBCSCRIPTION = "0";
public static final String QUERY_TMP_SUBCSCRIPTION = "1";
public static final String BOSS_CHARGE_FEE_OPCODE = "BOSS_CHARGE_FEE";
public static final String BOSS_ADD_CONFIRM = "BOSS_ADD_CONFIRM";
public static final String BOSS_DEL_CONFIRM = "BOSS_DEL_CONFIRM";
public static final int ALARM = 1;
public static final int NORMAL = 0;
public static final int UNUSE = 2;
public static final String DOC_VERSION_31 = "3.1";
public static final String DOC_VERSION_30 = "3.0";
public static final String DOC_BILLING = "0";
public static final String DOC_USE_RECORED = "1";
public static final String DOC_USER_STATUS_NATURAL = "O";
public static final String DOC_USER_STATUS_ERROR = "E";
public static final String DOC_USER_STATUS_LOGOUT = "L";
public static final String DOC_RIGTHS = "0";
public static final String DOC_NOT_RIGTHS = "1";
public static final String DB_PRODUCT_STATUS_NATURAL = "0";
public static final String DB_PRODUCT_STATUS_PAUSE = "1";
public static final String DB_PRODUCT_STATUS_ERROR = "2";
public static final String DB_PRODUCT_CHARGE_MODE_TIMES = "0";
public static final String DB_PRODUCT_CHARGE_MODE_MONTH = "1";
public static final String DB_PRODUCT_TYPE_PRODUCT = "0";
public static final String DB_PRODUCT_TYPE_SUITE = "1";
public static final String DB_SERVICE_STATUS_NOMAL = "0";
public static final String DB_SERVICE_STATUS_ERROR = "1";
public static final String DB_USER_STATUS_SLEEP = "01";
public static final String DB_USER_STATUS_NORMAL = "02";
public static final String DB_USER_STATUS_STOP = "03";
public static final String DB_USER_STATUS_LOGOUT = "04";
public static final String DB_USER_STATUS_ARREAR = "05";
public static final String DB_USER_STATUS_SUSPEND = "06";
public static final String DB_USER_STATUS_BLACKLIST = "07";
public static final String DB_USER_STATUS_ERROR = "08";
public static final String DOC_CMS_DELETED = "Deleted";
public static final String DB_BMS_NODE_ID = "BMS";
public static final String DB_CMS_NODE_ID = "CMS";
public static final String DB_IEPG_NODE_ID = "IEPG";
public static final String DB_OPERATION_ID_BOSS = "BOSS";
public static final String DB_OPERATION_ID_PORTAL = "PORTAL";
public static final String DB_OPERATION_ID_MD = "MD";
public static final String DB_OPERATION_TYPE_ADD = "0";
public static final String DB_OPERATION_TYPE_UPDATE = "1";
public static final String DB_OPERATION_TYPE_DEL = "2";
public static final String DB_CDR_SUCCEED = "0";
public static final String DB_CDR_USER_OUT = "1";
public static final String DB_CDR_SYSERROR = "2";
public static final String DB_CDR_ENDREASON_SUCCEED = "1000";
public static final String DB_CDR_ENDREASON_USER_OUT = "1001";
public static final String DB_CDR_ENDREASON_SYSERROR = "2000";
public static final String DB_CDR_TYPE_MEDIA = "01";
public static final String DB_CDR_TYPE_DOWNLOD = "02";
public static final String DB_GROUP_STATUS_NORMAL = "0";
public static final String DB_GROUP_STATUS_ERROR = "1";
public static final String DB_GROUP_USER_ALREADY_RELATION = "Y";
public static final String DB_GROUP_USER_NOT_RELATION = "N";
public static final String DB_GROUP_OWNER_BOSS = "0";
public static final String DB_GROUP_OWNER_BMS = "1";
public static final String DB_USER_CLASS_NORMAL = "0";
public static final String DB_USER_CLASS_TEST1 = "1";
public static final String DB_USER_CLASS_TEST2 = "2";
public static final String DB_USER_CLASS_TEST3 = "3";
public static final String DOC_USER_CLASS_NORMAL = "0";
public static final String DOC_USER_CLASS_TEST1 = "1";
public static final String DOC_USER_CLASS_TEST2 = "2";
public static final String DOC_USER_CLASS_TEST3 = "3";
public static final String DB_USER_GROUP_DEFAULT = "1000";
public static final String DB_PROMOTION_MODE_DISCOUNT = "0";
public static final String DB_PROMOTION_MODE_DEDUCT = "1";
public static final String DOC_PROMOTION_MODE_DISCOUNT = "0";
public static final String DOC_PROMOTION_MODE_DEDUCT = "1";
public static final String DB_SP_STATUS_PAUSER = "0";
public static final String DB_SP_STATUS_ERROR = "1";
public static final String DB_SP_STATUS_NORMAL = "2";
public static final String DOC_SP_STATUS_PAUSER = "0";
public static final String DOC_SP_STATUS_ERROR = "1";
public static final String DOC_SP_STATUS_NORMAL = "2";
public static final String DB_SP_TYPE_SP = "1";
public static final String DB_SP_TYPE_CP = "2";
public static final String DOC_IS_NEW = "0";
public static final String DOC_IS_OLD = "1";
public static final String DOC_AUTH_TYPE_RESOURCE = "0";
public static final String DOC_AUTH_TYPE_PRODUCT = "1";
public static final String DOC_CHARGE_MODE_MONTHLY = "0";
public static final String DOC_CHARGE_MODE_TIMES = "1";
public static final String DOC_SUB_STATUS_NORMAL = "1";
public static final String DOC_SUB_STATUS_PAUSER = "2";
public static final String DB_SUB_ORDER_TYPE_ONCE = "0";
public static final String DB_SUB_ORDER_TYPE_MONTHLY = "1";
public static final String DOC_SUB_ORDER_TYPE_MONTHLY = "2";
public static final String DOC_SUB_ORDER_TYPE_ONCE = "1";
public static final String DB_SUB_OWNER_BOSS = "0";
public static final String DB_SUB_OWNER_MD = "1";
public static final String DB_SUB_OWNER_PORTAL = "2";
public static final String DB_SUB_STATUS_NORMAL = "1";
public static final String DB_SUB_STATUS_PAUSE = "2";
public static final String DB_SUB_STATUS_CANCEL = "3";
public static final String DB_SUB_STATUS_PROCESS = "4";
public static final String DB_SUB_STATUS_FAIL = "5";
public static final String DB_SUB_STATUS_ARREARAGE = "11";
public static final String DB_SUB_STATUS_MANAGER = "12";
public static final String DB_SUB_STATUS_PRE_CANCEL = "13";
public static final String DB_SUB_STATUS_NOT_ENOUGH = "14";
public static final String DB_SUBCSCRIPTION_TYPE_PERSON = "1";
public static final String DB_SUBCSCRIPTION_TYPE_OTHER = "2";
public static final String DB_SUBCSCRIPTION_TYPE_GROUPTOPERSON = "3";
public static final String DB_SUBCSCRIPTION_TYPE_GROUP = "4";
public static final String DB_SUB_VALID_STATUS_NORMAL = "0";
public static final String DB_SUB_VALID_STATUS_CANCEL = "1";
public static final String DB_SUB_VALID_STATUS_SLEEP = "2";
public static final String DB_PRICE_POLICY_HIGHT = "0";
public static final String DB_PRICE_POLICY_MIDDLE = "1";
public static final String DB_PRICE_POLICY_LOW = "2";
public static final int DB_SYNC_TYPE_SUBSCRIPTION = 0;
public static final int DB_SYNC_TYPE_USER = 1;
public static final int DB_SYNC_TYPE_NOT_PAY_BILLING = 2;
public static final int DB_SYNC_TYPE_BILLING = 3;
public static final int DB_SYNC_TYPE_USE_RECORED = 4;
public static final int DB_SYNC_TYPE_CHECK_PERIOD = 5;
public static final int DB_SYNC_TYPE_CHECK_TIMES = 6;
public static final int DB_SYNC_TYPE_USER_BILLING = 7;
public static final int DB_SYNC_TYPE_USER_USE_RECORED = 8;
public static final int DB_SYNC_TYPE_PRODUCT_SUB_QUANTITY = 9;
public static final int DB_SYNC_TYPE_CHANNEL_SUB_QUANTITY = 10;
public static final int DB_SYNC_TYPE_SUB_3TH = 11;
public static final String AUTH_TYPE_PRODUCT = "0";
public static final String AUTH_TYPE_SERVICE = "1";
public static final String DB_GROUP_TYPE_VIRTUAL = "1";
public static final String DB_GROUP_TYPE_BOSS = "2";
public static final String DB_GROUP_TYPE_REGION = "3";
public static final String DB_GROUP_TYPE_IP = "4";
public static final String DB_AUTH_TYPE_ONCE_ = "0";
public static final String DB_AUTH_TYPE_MOTH_ = "1";
public static final String DB_AUTH_STATUS_NORMAL = "0";
public static final String DB_AUTH_STATUS_ERROR = "1";
public static final String DOC_PORTAL_SUB_STATUS_NORMAL = "0";
public static final String DOC_PORTAL_SUB_STATUS_ERROR = "1";
public static final String DOC_PORTAL_SUB_STATUS_PROCESS = "2";
public static final String DOC_PORTAL_SUB_STATUS_CANCEL = "3";
public static final Integer DB_REAL_UNAVAILABLE = Integer.valueOf(0);
public static final Integer DB_REAL_AVAILABLE = Integer.valueOf(1);
public static final String DB_GOODS_USERABLE = "1";
public static final String DB_GOODS_PASSABLE = "0";
public static final String DB_CHARGE_MODE_ONCE = "0";
public static final String DB_CHARGE_MODE_PERIOD = "1";
public static final String DB_CHARGE_MODE_FREE = "2";
public static final String DB_PURCHASE_ONE_TYPE = "0";
public static final String DB_PURCHASE_MONTHLY_TYPE = "1";
public static final String DB_SUBCSCRIPTION_NORMAL_STATUS = "1";
public static final String DB_SUBCSCRIPTION_PAUSE_STATUS = "2";
public static final String DB_SUBCSCRIPTION_CANCEL_STATUS = "3";
public static final String DB_USERSTATE_NOT_ACTIVATE = "01";
public static final String DB_USERSTATE_NATURAL = "02";
public static final String DB_USERSTATE_STOP = "03";
public static final String DB_USERSTATE_LOGOUT = "04";
public static final String DB_USERSTATE_ARREAR = "05";
public static final String DB_USERSTATE_SUSPEND = "06";
public static final String DB_USERSTATE_BLACKLIST = "07";
public static final String DB_USERSTATE_ERROR = "08";
public static final Integer CHANNEL_STATUS_UN_USER = Integer.valueOf(0);
public static final String BOSS_CONVERT_INTEGRAL = "AAA_CONVERT_INTEGRAL";
public static final String DB_BILLINGSTATUS_NATURAL = "0";
public static final String DB_BILLINGSTATUS_ARREAR = "1";
public static final String DB_PRICE_DISCOUNT = "0";
public static final String DB_PRICE_LARGESS = "1";
public static final String DB_SUBCSCRIPTION_PERSON_TYPE = "1";
public static final String DB_SUBCSCRIPTION_OTHER_TYPE = "2";
public static final String DB_SUBCSCRIPTION_GROUPTOPERSON_TYPE = "3";
public static final String DB_SUBCSCRIPTION_GROUP_TYPE = "4";
public static final String SUBCSCRIPTION_NORMAL_VALID_STATUS = "0";
public static final String SUBCSCRIPTION_CANCEL_VALID_STATUS = "1";
public static final String SUBCSCRIPTION_READY_VALID_STATUS = "2";
public static final String DB_BOSS_OPERATION_ID = "BOSS";
public static final String DB_IEPG_OPERATION_ID = "IEPG";
public static final String PRICE_POLICY_HIGHT = "0";
public static final String PRICE_POLICY_MIDDLE = "1";
public static final String PRICE_POLICY_LOW = "2";
public static final int PO_READY_AUDITING = 0;
public static final int PO_READY_TEST = 1;
public static final int PO_COMMERCIAL = 2;
public static final int PO_READY_DOWN_LINE = 3;
public static final int PO_DOWN_LINE = 4;
public static final String DOC_GOODSSTATE_NATURAL = "1";
public static final String DB_CDR_NOT_START = "01";
public static final String DB_CDR_PLAYING = "02";
public static final String DB_CDR_END = "03";
public static final String DB_CDR_FINAL = "04";
public static final String DB_CDR_STOP = "05";
public static final String DB_CDR_RESUME = "06";
public static final int CHANNEL_UNAVAILABLE = 0;
public static final int CHANNEL_AVAILABLE = 1;
public static final String VOD_TYPE = "1";
public static final String BTV_TYPE = "2";
public static final String TTV_TYPE = "3";
public static final String NPVR_TYPE = "4";
public static final String BOSS_USERSTATE_NATURAL = "O";
public static final String BOSS_USERSTATE_STOP = "S";
public static final String BOSS_USERSTATE_LOGOUT = "D";
public static final String BOSS_USERSTATE_ERROR = "E";
public static final String DOC_USERSTATE_NATURAL_BOSS = "O";
public static final String DOC_USERSTATE_ERROR_BOSS = "E";
public static final String BMS_USERSTATE_NATURAL = "O";
public static final String BMS_USERSTATE_ERROR = "E";
public static final String DOC_CHARGEMODE_PAY_MONTHLY = "0";
public static final String DOC_CHARGEMODE_TIMES = "1";
public static final int SUBSCRIPTION_TYPE = 0;
public static final int USER_TYPE = 1;
public static final int NOTPAY_BILLING_TYPE = 2;
public static final int BILLING_TYPE = 3;
public static final int USE_RECORED_TYPE = 4;
public static final int CHECK_PERIOD_TYPE = 5;
public static final int CHECK_TIMES_TYPE = 6;
public static final int USER_BILLING_TYPE = 7;
public static final int USER_USE_RECORED_TYPE = 8;
public static final int SUBSCRIPTION_TO_MDH_TYPE = 9;
public static final String DOC_ACROSS = "0";
public static final String DOC_NOT_ACROSS = "1";
public static final String TEST_USER_CREDITGRADE = "B";
public static final String TEST_USER_RANK = "2";
public static final String TEST_USER_CLASS = "1";
public static final String TEST_USER_AUTH_TYPE = "C";
public static final String TEST_USER_PAY_TYPE = "0";
public static final String TEST_USER_DEFAULT_REGION = "1";
public static final String TEST_USER_CM_MAC = "000-000-000";
public static final String TEST_USER_USER_TYPE = "1";
public static final String TEST_USER_USER_OWNER = "1";
public static final String BOSS_USER_TYPE = "0";
public static final String BOSS_USER_OWNER = "0";
public static final String PRODUCT_PPV_ORDERTYPE_RESOURCE = "0";
public static final String PRODUCT_PPV_ORDERTYPE_PRODUCT = "1";
public static final String PRODUCT_IS_REPEAT_ORDER = "0";
public static final String PRODUCT_IS_NOT_REPEAT_ORDER = "1";
public static final String PRODUCT_IS_BASE_AUTH = "0";
public static final String PRODUCT_IS_NOT_BASE_AUTH = "1";
public static final String SUBSCRIPTION_NOT_EXIST = "0";
public static final String SUBSCRIPTION_EXIST = "1";
public static final String PURCHASETYPE_ORDER = "0";
public static final String PURCHASETYPE_RENEWAL = "1";
public static final String PROVIDER_UNAVAILABLE = "0";
public static final String PROVIDER_AVAILABLE = "1";
}
package com.XXXXXX.dhm.aaa.commons.util;
import com.XXXXXX.dhm.aaa.commons.constant.SerStateCode;
import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.log4j.Logger;
public class StringUtil
{
private static Logger logger = Logger.getLogger(StringUtil.class);
public static final int NUMBER = 1;
public static final int TEXT = 2;
public static final int CHAR = 3;
public static final int REGEXP = 4;
public static final int DATE = 5;
public static final int DOUBLE = 6;
public static final int NUM_AND_CHAR = 7;
public static final int CHAR_TWO = 8;
public static final int NOT_CHECK_LEN = -1;
public static final String FORMAT_STYLE = "0.###";
public static final String FORMAT_STYLE_LEN_TWO = "0.##";
public static final String RATIONAL_NUMBERS_REGEXP = "^(-?\\d+)(\\.\\d+)?$";
public static final String NUMBERS_AND_CHAR_REGEXP = "^[A-Za-z0-9]+$";
public static final String LEGALCHAR_REGEXP = "^\\w+$";
public static boolean isNumAndChar(String str)
{
if ((str == null) || (str.equals("")))
{
return false;
}
Pattern pattern = Pattern.compile("^[A-Za-z0-9]+$");
Matcher match = pattern.matcher(str);
boolean b = match.matches();
return b;
}
public static String getIndexStr(int index, int maxLen)
{
String indexStr = String.valueOf(index);
int len = indexStr.length();
for (; len < maxLen; ++len)
{
indexStr = "0" + indexStr;
}
return indexStr;
}
public static boolean isDouble(String str)
{
if ((str == null) || (str.equals("")))
{
return false;
}
Pattern pattern = Pattern.compile("^(-?\\d+)(\\.\\d+)?$");
Matcher match = pattern.matcher(str);
boolean b = match.matches();
return b;
}
public static boolean isInteger(String str)
{
if ((str == null) || (str.equals("")))
{
return false;
}
Pattern pattern = Pattern.compile("(^(0|[1-9]\\d*)$|^(-([1-9]\\d*))$)");
Matcher match = pattern.matcher(str);
boolean b = match.matches();
return b;
}
public static boolean isLegalChar(String Str)
{
if ((Str == null) || (Str.equals("")))
{
return false;
}
Pattern pattern = Pattern.compile("^\\w+$");
Matcher match = pattern.matcher(Str);
boolean b = match.matches();
return b;
}
public static boolean isChina(String str)
{
String chinese = "[一-龥]";
for (int i = 0; i < str.length(); ++i)
{
String test = str.substring(i, i + 1);
if (test.matches(chinese))
{
return true;
}
}
return false;
}
public static boolean checkData(String str, int type, boolean flag, int maxLen)
{
return checkData(str, type, flag, maxLen, null, null);
}
public static boolean checkMapData(String str, boolean flag, String regexp)
{
return checkData(str, 4, flag, -1, null, regexp);
}
public static boolean checkDate(String str, boolean flag, String formatStr)
{
return checkData(str, 5, flag, -1, formatStr, null);
}
public static boolean equals(String str, String str1)
{
return getString(str).equals(getString(str1));
}
private static boolean checkData(String str, int type, boolean flag, int maxLen, String formatStr, String regexp)
{
if ((!flag) && (isNil(str)))
{
return true;
}
if ((type != 6) && ((
(isNil(str)) || ((maxLen != -1) && (getJava2OracleLength(str) > maxLen)))))
{
return false;
}
try
{
switch (type)
{
case 1:
return isNumeric(str);
case 2:
return true;
case 5:
if ((str == null) || (formatStr == null))
{
return false;
}
if (DateUtil.format(str, formatStr) == null)
{
return false;
}
case 3:
return isLegalChar(str);
case 4:
Pattern p = Pattern.compile(regexp);
Matcher m = p.matcher(str);
return m.matches();
case 6:
if (isDouble(str))
{
Double dou = Double.valueOf(Double.parseDouble(str));
if (String.valueOf(dou.doubleValue()).length() > maxLen)
{
return false;
}
}
else
{
return false;
}
case 7:
return isNumAndChar(str);
case 8:
return isNumAndChar(str.replaceAll("-", ""));
}
return false;
}
catch (Exception e)
{
logger.error(e.getMessage(), e);
return false;
}
return true;
}
public static boolean isNumeric(String str)
{
if ((str != null) && (!str.trim().equals("")))
{
Pattern pattern = Pattern.compile("[0-9]*");
Matcher isNum = pattern.matcher(str);
if (isNum.matches())
{
return true;
}
}
return false;
}
public static String getString(String str)
{
return (str == null) ? "" : str;
}
public static String getString(Double str)
{
return (str == null) ? "" : String.valueOf(str);
}
public static String getString(Long str)
{
return (str == null) ? "" : String.valueOf(str);
}
public static String getString(Integer str)
{
return (str == null) ? "" : String.valueOf(str);
}
public static String convert2Html(String origine)
{
String outStr = null;
if (origine != null)
{
String tmp = replace(origine, ">", ">");
String tmp2 = replace(tmp, "<", "<");
String tmp3 = replace(tmp2, " ", " ");
String tmp4 = replace(tmp3, "\r\n", "<br>");
outStr = tmp4;
}
else
{
outStr = "";
}
return outStr;
}
public static String replace(String str, String old, String rep)
{
if ((str == null) || (old == null) || (rep == null))
{
return "";
}
int index = str.indexOf(old);
if ((index < 0) || (old.equals("")))
{
return str;
}
StringBuffer strBuf = new StringBuffer(str);
while (index >= 0)
{
strBuf.delete(index, index + old.length());
strBuf.insert(index, rep);
index = strBuf.toString().indexOf(old);
}
return strBuf.toString();
}
public static String getRandom(int index)
{
int randomIndex = -1;
StringBuffer randomID = new StringBuffer("");
Double medianRandom = null;
char[] randomElement = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
for (int i = 0; i < index; ++i)
{
medianRandom = Double.valueOf(Math.random() * 998.0D);
randomIndex = medianRandom.intValue() % 10;
randomID.append(String.valueOf(randomElement[randomIndex]));
}
return randomID.toString();
}
public static String getRandomZeroAndOne(int index)
{
int randomIndex = -1;
StringBuffer randomID = new StringBuffer("");
Double medianRandom = null;
char[] randomElement = { '0', '1', '0', '1', '1', '0', '1', '0', '1', '1' };
for (int i = 0; i < index; ++i)
{
medianRandom = Double.valueOf(Math.random() * 998.0D);
randomIndex = medianRandom.intValue() % 10;
randomID.append(String.valueOf(randomElement[randomIndex]));
}
return randomID.toString();
}
public static boolean isNil(String string)
{
return (string == null) || (string.trim().length() == 0);
}
public static String getXMLStrFromObj(Object obj)
{
XStream xstream = new XStream(new DomDriver());
String xmlStr = xstream.toXML(obj);
return xmlStr;
}
public static Object getObjFromXMLStr(String xmlStr)
{
XStream xstream = new XStream(new DomDriver());
Object obj = xstream.fromXML(xmlStr);
return obj;
}
public static boolean checkValidate(String regex, String value, boolean isNull)
{
if ((!isNull) && (isNil(value)))
{
return true;
}
if (isNil(value))
{
return false;
}
return checkValidate(regex, value);
}
public static boolean checkValidate(String regex, String value)
{
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(value);
return m.matches();
}
public static boolean checkDate(String str, String formatStr)
{
if ((str == null) || (formatStr == null))
{
return false;
}
return DateUtil.format(str, formatStr) != null;
}
public static String dataFormat(double value, String dataFormatStyle)
{
try
{
DecimalFormat df = new DecimalFormat(dataFormatStyle);
return df.format(value);
}
catch (Exception e)
{
}
return String.valueOf(value);
}
public static int getJava2OracleLength(String value)
{
if (value == null)
{
return 0;
}
if (value.length() == value.getBytes().length)
{
return value.length();
}
int len = 0;
char[] charArr = value.toCharArray();
for (int i = 0; i < charArr.length; ++i)
{
if (String.valueOf(charArr[i]).matches("[^x00-xff]"))
{
len += 3;
}
else
{
++len;
}
}
return len;
}
public static int getLengthInOracle(String value)
{
int length = 0;
try
{
if (!isNil(value))
{
length = value.getBytes("UTF-8").length;
}
}
catch (UnsupportedEncodingException e)
{
logger.error(e.getMessage(), e);
}
return length;
}
public static String dataFormat(float value, String dataFormatStyle)
{
try
{
DecimalFormat df = new DecimalFormat(dataFormatStyle);
return df.format(value);
}
catch (Exception e)
{
}
return String.valueOf(value);
}
public static void main(String[] args)
{
}
public static Integer convertStatus(String oldStatus)
{
Integer status = SerStateCode.DB_REAL_UNAVAILABLE;
if (oldStatus != null)
{
if ("Available".toLowerCase().equals(oldStatus.trim().toLowerCase()))
{
return SerStateCode.DB_REAL_AVAILABLE;
}
if ("Loading".toLowerCase().equals(oldStatus.trim().toLowerCase()))
{
return SerStateCode.DB_REAL_AVAILABLE;
}
}
return status;
}
}
提到代理,我们可以使用ProxyBeanFactory,并配置proxyInterfaces,target和interceptorNames实现,但如果需要代理的bean很多,无疑会对spring配置文件的编写带来繁重的工作
Spring为我们提供了,根据beanName匹配后进行自动代理的解决方法
业务接口
业务实现类A,作为配置文件中的buyBean:
业务实现类B,作为配置文件中的sellBean:
切面通知:
配置文件:
其中beanNames为buy*,意味着所有以buy开头的bean,都被spring容易自动代理,执行相应的切面通知
测试代码:
在测试代码中,我们的buyBean打印两条买的信息,sellBean打印两条卖的信息,可以看到buyBean执行的方法已经进行了切面处理
需要注意的是,如果使用自动代码,则获得Spring Bean工厂要用
ApplicationContext ctx=new FileSystemXmlApplicationContext(filePath);
而不能用
BeanFactory factory=new XmlBeanFactory(new FileSystemResource(filePath));
原因我想是因为BeanFactory在初始化时并不实例化单例的Bean,而ApplicationContext则在初始化时候全部实例化了Bean,自动代理需要在初始化时候定义好代理关系
反射工具类:
/*
* 工 程 名: portalMS
* 包 名: com.xxx.dhm.portalMS.common.util
* 文 件 名: ReflectUtil.java
* 版 权: Copyright (c) 2009 xxx All Rights Reserved.
* 描 述: JAVA反射工具
* 修 改 人:
* 修改时间:
* 跟踪单号: <跟踪单号>
* 修改单号: <修改单号>
* 修改内容: <修改内容>
*/
package com.coship.dhm.portalMS.common.util;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
/**
*
* 反射工具类
*
* @author
* @version
* @since
*/
public class ReflectUtil
{
private static final Log logger = LogFactory.getLog(ReflectUtil.class);
@SuppressWarnings("unchecked")
public static void setFieldValue(Object target, String fname, Class ftype,
Object fvalue)
{
if (target == null
|| fname == null
|| "".equals(fname)
|| (fvalue != null && !ftype.isAssignableFrom(fvalue.getClass())))
{
return;
}
Class clazz = target.getClass();
try
{
Field field = clazz.getDeclaredField(fname);
if (!Modifier.isPublic(field.getModifiers()))
{
field.setAccessible(true);
}
field.set(target, fvalue);
}
catch (Exception me)
{
if (logger.isDebugEnabled())
{
logger.debug(me);
}
}
}
/**
* 通过反射机制克隆一个对象
* @param obj
* @return
* @throws Exception
*/
public static Object copyObject(Object obj) throws Exception
{
Field[] fields = obj.getClass().getDeclaredFields();
Object newObj = obj.getClass().newInstance();
for (int i = 0, j = fields.length; i < j; i++)
{
String propertyName = fields[i].getName();
Object propertyValue = getProperty(obj, propertyName);
setProperty(newObj, propertyName, propertyValue);
}
return newObj;
}
// 反射调用setter方法,进行赋值
@SuppressWarnings("unchecked")
private static Object setProperty(Object bean, String propertyName,
Object value) throws Exception
{
Class clazz = bean.getClass();
try
{
Field field = clazz.getDeclaredField(propertyName);
Method method = clazz.getDeclaredMethod(getSetterName(field.getName()),
new Class[] { field.getType() });
return method.invoke(bean, new Object[] { value });
}
catch (Exception e)
{
throw e;
}
}
// 反射调用getter方法,得到field的值
@SuppressWarnings("unchecked")
public static Object getProperty(Object bean, String propertyName) throws Exception
{
Class clazz = bean.getClass();
try
{
Field field = clazz.getDeclaredField(propertyName);
Method method = clazz.getDeclaredMethod(getGetterName(field.getName()),
new Class[] {});
return method.invoke(bean, new Object[] {});
}
catch (Exception e)
{
throw e;
}
}
// 根据field名,得到getter方法名
private static String getGetterName(String propertyName)
{
String method = "get" + propertyName.substring(0, 1).toUpperCase()
+ propertyName.substring(1);
return method;
}
// 根据field名,得到setter方法名
private static String getSetterName(String propertyName)
{
String method = "set" + propertyName.substring(0, 1).toUpperCase()
+ propertyName.substring(1);
return method;
}
/**
* 普通的JavaBean对象转换成Map数据类型。
* 将普通的JavaBean对象转换成Map数据类型,其中JavaBean声明的变量名作为Map类型的key,
* 该变量的值,作为其Map数据类型相应key的值。
*
* @param obj
* - 普通JavaBean对象
* @return 返回Map数据类类型
*
* @return Map<String,Object> 返回Map数据类型
*/
@SuppressWarnings("unchecked")
public static Map<String, Object> getObjectAsMap(Object obj)
{
Map<String, Object> map = new HashMap<String, Object>();
if (obj == null)
{
return map;
} else if ( obj instanceof Map ) {
return (Map) obj;
}
Class clazz = obj.getClass();
Method[] methods = clazz.getMethods();
String methodname = "";
for (int i = 0; i < methods.length; i++)
{
methodname = methods[i].getName();
if (methodname.startsWith("get"))
{
try
{
Object value = methods[i].invoke(obj);
if( value != null && (value instanceof String ) ) {
String str = (String) value;
value = str.trim();
}
map.put(getFieldName(methodname), value);
}
catch (IllegalArgumentException e)
{
logger.debug("Convert JavaBean to Map Error!", e);
}
catch (IllegalAccessException e)
{
logger.debug("Convert JavaBean to Map Error!", e);
}
catch (InvocationTargetException e)
{
logger.debug("Convert JavaBean to Map Error!", e);
}
}
}
return map;
}
private static String getFieldName(String str)
{
String firstChar = str.substring(3, 4);
String out = firstChar.toLowerCase() + str.substring(4);
return out;
}
}
在方法类打印日志:
package com.xxxxxx.dhm.portalMS.common;
import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PersistenceDelegate;
import java.beans.PropertyDescriptor;
import java.beans.XMLEncoder;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.io.StringWriter;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.Timestamp;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import com.sun.org.apache.xml.internal.serialize.OutputFormat;
import com.sun.org.apache.xml.internal.serialize.Serializer;
import com.sun.org.apache.xml.internal.serialize.SerializerFactory;
import com.sun.org.apache.xml.internal.serialize.XMLSerializer;
/**
* debug日志包装类。
*/
public class DebugLogHelper
{
/** 写日志的类 */
private Class<?> cls;
/** 系统配置的日志对象 */
private Logger debugLogger;
/** 不同版本jdk对应类信息在堆栈中的索引 */
private Integer jdkIndex;
/** 系统换行分隔符 */
private static final String LINESEPARATOR = System.getProperty("line.separator");
/**
* 构造方法。
* @param cls 写日志的类。
*/
public DebugLogHelper(Class<?> cls)
{
try
{
this.cls = cls;
debugLogger = Logger.getLogger(cls);
}
catch (Exception e)
{
System.out.println("Open DebugLog is Error!");
}
}
/**
* 进行方法的日志入口。
* @param objects 要打印的参数(N)。
*/
public void enterFuncDebugLog(Object... objects)
{
if (!isDebugEnable())
{
return;
}
try
{
StackTraceElement[] eles = Thread.currentThread().getStackTrace();
int index = getMethodIndex(eles);
String methodName = eles[index].getMethodName();
Integer num = eles[index].getLineNumber();
StringBuffer str = new StringBuffer();
str.append("[");
str.append(Thread.currentThread().hashCode());
str.append("]");
str.append("[----Enter----]" + methodName + "." + num + "[Params");
if (objects == null || objects.length == 0)
{
str.append("(null)");
}
else
{
str.append(LINESEPARATOR + "(");
str.append(LINESEPARATOR + "<Param>");
for (int i = 0; i < objects.length; i++)
{
str.append(LINESEPARATOR);
str.append("<Param" + (i + 1) + ">").append(LINESEPARATOR);
String foramtParam = appendParam(null, objects[i]);
if (null != foramtParam)
{
str.append(foramtParam);
str.deleteCharAt(str.length() - 1);
}
else
{
str.append(convertObjectToXml(objects[i]));
}
str.append(LINESEPARATOR).append("</Param" + (i + 1) + ">");
}
str.append(LINESEPARATOR).append("<Param>");
str.append(LINESEPARATOR + ")");
}
debugLogger.debug(str.toString());
}
catch (Throwable e)
{
debugLogger.debug(e.toString());
}
}
/**
* 在方法的内打日志入口。
* @param objects 要打印的参数(N)。
*/
public void atFuncDebugLog(Object... objects)
{
if (!isDebugEnable())
{
return;
}
try
{
StackTraceElement[] eles = Thread.currentThread().getStackTrace();
int index = getMethodIndex(eles);
String methodName = eles[index].getMethodName();
Integer num = eles[index].getLineNumber();
StringBuffer str = new StringBuffer();
str.append("[");
str.append(Thread.currentThread().hashCode());
str.append("]");
str.append("[----At-------]" + methodName + "." + num + "[Params]");
if (objects == null || objects.length == 0)
{
str.append("(null)");
}
else
{
str.append("( ");
for (int i = 0; i < objects.length; i++)
{
if (objects[i] != null)
{
str.append(appendParam(null, objects[i]));
}
}
str.deleteCharAt(str.length() - 1);
str.append(" )");
}
debugLogger.debug(str.toString());
}
catch (Throwable e)
{
debugLogger.debug("[Exception][Function]atFuncDebugLog[Description]"
+ e.toString());
}
}
/**
* 在方法的内打日志入口。
* @param desc 描述
* @param object 要打印的参数。
*/
public void atFuncDebugLog(String desc, Object object)
{
if (!isDebugEnable())
{
return;
}
try
{
StackTraceElement[] eles = Thread.currentThread().getStackTrace();
int index = getMethodIndex(eles);
String methodName = eles[index].getMethodName();
Integer num = eles[index].getLineNumber();
StringBuffer str = new StringBuffer();
str.append("[");
str.append(Thread.currentThread().hashCode());
str.append("]");
str.append("[----At-------]" + methodName + "." + num + "[Params]");
str.append("( ");
str.append(appendParam(desc, object));
str.deleteCharAt(str.length() - 1);
str.append(" )");
debugLogger.debug(str.toString());
}
catch (Throwable e)
{
debugLogger.debug("[Exception][Function]atFuncDebugLog[Description]"
+ e.toString());
}
}
/**
* 退出方法异常的日志入口。
* @param object 要打印的参数。
*/
public void exitFuncDebugLog(Object obj)
{
if (!isDebugEnable())
{
return;
}
try
{
StackTraceElement[] eles = Thread.currentThread().getStackTrace();
int index = getMethodIndex(eles);
String methodName = eles[index].getMethodName();
StringBuffer str = new StringBuffer();
str.append("[");
str.append(Thread.currentThread().hashCode());
str.append("]");
str.append("[----Exit-----]" + methodName + "[Results]");
if (obj == null)
{
str.append("null");
}
else
{
str.append("( ");
str.append(appendParam(null, obj));
str.deleteCharAt(str.length() - 1);
str.append(" )");
}
debugLogger.debug(str.toString());
}
catch (Throwable e)
{
debugLogger.debug("[Exception][Function]exitFuncDebugLog[Description]"
+ e.toString());
}
}
/**
* 退出方法的日志入口。
*/
public void exitFuncDebugLog()
{
if (!isDebugEnable())
{
return;
}
try
{
StackTraceElement[] eles = Thread.currentThread().getStackTrace();
int index = getMethodIndex(eles);
String methodName = eles[index].getMethodName();
Integer num = eles[index].getLineNumber();
StringBuffer str = new StringBuffer();
str.append("[");
str.append(Thread.currentThread().hashCode());
str.append("]");
str.append("[----Exit-----]" + methodName + "." + num
+ "[Resultss]");
str.append("void");
debugLogger.debug(str.toString());
}
catch (Throwable e)
{
debugLogger.debug("[Exception][Function]exitFuncDebugLog[Description]"
+ e.toString());
}
}
/**
* 方法异常的日志入口。
* @param desc 描述
* @param object 要打印的参数。
*/
public void excepFuncDebugLog(Object obj)
{
excepFuncDebugLog("", obj);
}
/**
* 方法异常的日志入口。
* @param desc 描述
* @param object 要打印的参数。
*/
public void excepFuncDebugLog(String message, Object obj)
{
try
{
StackTraceElement[] eles = Thread.currentThread().getStackTrace();
int index = getMethodIndex(eles);
String methodName = eles[index].getMethodName();
Integer num = eles[index].getLineNumber();
StringBuffer str = new StringBuffer();
str.append("[");
str.append(Thread.currentThread().hashCode());
str.append("]");
str.append("[----Exception----]" + methodName + "." + num);
str.append(":");
str.append(message);
str.append(LINESEPARATOR);
if (obj == null)
{
str.append("null");
}
else if (obj instanceof String)
{
str.append(obj);
}
else if (obj instanceof Exception)
{
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
((Exception)obj).printStackTrace(ps);
String result = baos.toString();
try
{
ps.close();
baos.close();
}
catch (IOException e1)
{
e1.printStackTrace();
}
str.append("( ");
str.append(result);
str.append(" )");
}
else
{
str.append("( ");
str.append(appendParam(null, obj));
str.deleteCharAt(str.length() - 1);
str.append(" )");
}
debugLogger.error(str.toString());
if (isDebugEnable())
{
debugLogger.debug(str.toString());
}
}
catch (Throwable e)
{
debugLogger.error("[Exception][Function]excepFuncDebugLog[Description]"
+ e.toString());
if (isDebugEnable())
{
debugLogger.debug("[Exception][Function]excepFuncDebugLog[Description]"
+ e.toString());
}
}
}
/**
* 获取当前类线程信息的方法。
* @param eles 栈信息
* @author 907440
* @version [2014-01-28]
*/
private int getMethodIndex(StackTraceElement[] eles)
{
// 如果已经正确取得一次索引,将直接返回。
if (null != jdkIndex)
{
return jdkIndex.intValue();
}
int index = 0;
for (StackTraceElement ele : eles)
{
// 默认错误时返回jdk1.6的索引.
if (index > 5)
{
index = 3;
break;
}
if (ele.getClassName().equals(cls.getName()))
{
jdkIndex = index;
break;
}
++index;
}
return index;
}
/**
* 获取当前类线程信息的方法。
* @param name 名称
* @param obj 要打印的参数。
* @author 907440
* @version [2014-01-28]
*/
private String appendParam(String name, Object obj)
{
StringBuffer strBuf = null;
try
{
strBuf = new StringBuffer();
if (obj == null)
{
strBuf.append(name);
strBuf.append("=");
strBuf.append("null,");
return String.valueOf(strBuf);
}
boolean isClassType = Integer.class.isAssignableFrom(obj.getClass())
|| Long.class.isAssignableFrom(obj.getClass())
|| Character.class.isAssignableFrom(obj.getClass())
|| Byte.class.isAssignableFrom(obj.getClass())
|| Boolean.class.isAssignableFrom(obj.getClass());
if (isClassType || String.class.isAssignableFrom(obj.getClass())
|| StringBuffer.class.isAssignableFrom(obj.getClass())
|| Double.class.isAssignableFrom(obj.getClass())
|| Float.class.isAssignableFrom(obj.getClass())
|| Date.class.isAssignableFrom(obj.getClass())
|| Number.class.isAssignableFrom(obj.getClass()))
{
strBuf.append(obj.getClass().getSimpleName());
strBuf.append(name == null ? "" : (":" + name));
strBuf.append(" = " + obj.toString() + ",");
}
else if (Map.class.isAssignableFrom(obj.getClass()))
{
Map<?, ?> map = (Map<?, ?>)obj;
if (map.isEmpty())
{
strBuf.append(map.getClass().getSimpleName() + "[],");
return String.valueOf(strBuf);
}
strBuf.append("\r" + map.getClass().getSimpleName());
strBuf.append(name == null ? "" : (":" + name));
strBuf.append("( size = " + map.size() + " ) = { ");
Set<?> keySet = map.entrySet();
for (Iterator<?> iter = keySet.iterator(); iter.hasNext();)
{
Map.Entry<?, ?> entry = (Map.Entry<?, ?>)iter.next();
Object listObj = entry.getKey();
if (listObj != null)
{
strBuf.append("\r\t[ " + appendParam(null, listObj));
strBuf.append(appendParam(null, entry.getValue()));
strBuf.deleteCharAt(strBuf.length() - 1);
strBuf.append(" ]");
}
}
strBuf.append("\r},");
}
else if (Collection.class.isAssignableFrom(obj.getClass()))
{
Collection<?> coll = (Collection<?>)obj;
if (coll.isEmpty())
{
strBuf.append(coll.getClass().getSimpleName() + "[],");
return String.valueOf(strBuf);
}
strBuf.append("\r" + coll.getClass().getSimpleName());
strBuf.append(name == null ? "" : (":" + name));
strBuf.append("( size = " + coll.size() + ") = { ");
for (Iterator<?> iter = coll.iterator(); iter.hasNext();)
{
Object listObj = iter.next();
if (listObj != null)
{
strBuf.append("\r\t[ " + appendParam(null, listObj));
strBuf.deleteCharAt(strBuf.length() - 1);
strBuf.append(" ]");
}
}
strBuf.append("\r},");
}
else if (org.dom4j.Node.class.isAssignableFrom(obj.getClass()))
{
if (org.dom4j.Document.class.isAssignableFrom(obj.getClass()))
{
org.dom4j.Document doc = (org.dom4j.Document)obj;
strBuf.append(doc.asXML());
}
else
{
org.dom4j.Node node = (org.dom4j.Node)obj;
strBuf.append(node.asXML());
}
strBuf.append(",");
}
else if (Node.class.isAssignableFrom(obj.getClass()))
{
if (Document.class.isAssignableFrom(obj.getClass()))
{
Document document = (Document)obj;
strBuf.append(DOM2String(document));
}
else
{
Node node = (Node)obj;
strBuf.append(node2String(node, true));
}
strBuf.append(",");
}
else
{
BeanInfo info = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] props = info.getPropertyDescriptors();
System.out.println(obj.getClass().getName());
System.out.println(obj.getClass().getSimpleName());
strBuf.append(obj.getClass().getName());
strBuf.append(name == null ? "" : (":" + name));
strBuf.append(" = ( ");
for (PropertyDescriptor prop : props)
{
String propName = prop.getName();
if (prop.getWriteMethod() == null
|| prop.getReadMethod() == null)
{
continue;
}
Method readMethod = prop.getReadMethod();
Object paramObj = invokeMethod(readMethod, obj);
if (obj == paramObj)
{
continue;
}
if (paramObj != null)
{
strBuf.append(appendParam(propName, paramObj));
}
}
strBuf.deleteCharAt(strBuf.length() - 1);
strBuf.append(" ),");
}
}
catch (Throwable e)
{
debugLogger.debug("[Exception][Function]appendParam[Description]"
+ e.toString());
}
return String.valueOf(strBuf);
}
/**
* 将对象过XMLEncode转换为String
*
* @param requestObject 请求对象
* @return String 对象转换后的String
*/
public String convertObjectToXml(Object requestObject)
{
ByteArrayOutputStream bo = new ByteArrayOutputStream();
BufferedOutputStream bos = new BufferedOutputStream(bo);
XMLEncoder xmlEncoder = new XMLEncoder(bos);
PersistenceDelegate pd = xmlEncoder.getPersistenceDelegate(Date.class);
xmlEncoder.setPersistenceDelegate(Timestamp.class, pd);
String content = null;
try
{
// 使用XML编码器写对象
xmlEncoder.writeObject(requestObject);
xmlEncoder.close();
content = bo.toString();
}
catch (Exception e)
{
e.printStackTrace();
}
finally
{
try
{
bos.close();
bo.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
return content;
}
/**
* 将DOM对象转换为String
* @param doc DOM对象
* @return String 对象转换后的String
*/
public String DOM2String(Document doc)
{
String docStr;
ByteArrayOutputStream outPut;
if (doc == null)
return null;
docStr = null;
outPut = null;
try
{
outPut = new ByteArrayOutputStream();
OutputFormat format = new OutputFormat(doc);
format.setIndenting(true);
format.setEncoding("UTF-8");
Serializer serializer = SerializerFactory.getSerializerFactory("xml")
.makeSerializer(outPut, format);
serializer.asDOMSerializer().serialize(doc);
docStr = new String(outPut.toByteArray(), "UTF-8");
}
catch (Exception ex)
{
}
finally
{
IOUtils.closeQuietly(outPut);
}
return docStr;
}
/**
* 将Node对象转换为String
* @param doc DOM对象
* @return String 对象转换后的String
*/
public final String node2String(Node node, boolean isPreserveSpace)
{
if (node == null)
return null;
if (node.getNodeType() == 9)
node = ((Document)node).getDocumentElement();
OutputFormat format = new OutputFormat(node.getOwnerDocument());
format.setEncoding("UTF-8");
format.setIndenting(false);
format.setPreserveSpace(isPreserveSpace);
StringWriter stringOut = new StringWriter();
XMLSerializer serial = new XMLSerializer(stringOut, format);
try
{
serial.asDOMSerializer();
serial.serialize((Element)node);
}
catch (IOException ex)
{
}
return stringOut.toString();
}
/**
* 通过反射获取内部属性对象。
* @param method 方法
* @param target 类
* @return Object 参数值
*/
public Object invokeMethod(Method method, Object target)
{
return invokeMethod(method, target, null);
}
/**
* 通过反射获取内部属性对象。
* @param method方法
* @param target 类
* @return Object 参数值
* @author 907440
* @version [2014-01-28]
*/
public Object invokeMethod(Method method, Object target, Object args[])
{
try
{
return method.invoke(target, args);
}
catch (IllegalAccessException ex)
{
handleReflectionException(ex);
throw new IllegalStateException((new StringBuilder(
"Unexpected reflection exception - ")).append(ex.getClass()
.getName()).append(": ").append(ex.getMessage()).toString());
}
catch (InvocationTargetException ex)
{
handleReflectionException(ex);
throw new IllegalStateException((new StringBuilder(
"Unexpected reflection exception - ")).append(ex.getClass()
.getName()).append(": ").append(ex.getMessage()).toString());
}
}
/**
* 处理异常
*
* @param ex 异常
*/
public void handleReflectionException(Exception ex)
{
if (ex instanceof NoSuchMethodException)
throw new IllegalStateException((new StringBuilder(
"Method not found: ")).append(ex.getMessage()).toString());
if (ex instanceof IllegalAccessException)
throw new IllegalStateException((new StringBuilder(
"Could not access method: ")).append(ex.getMessage())
.toString());
if (ex instanceof InvocationTargetException)
handleInvocationTargetException((InvocationTargetException)ex);
throw new IllegalStateException((new StringBuilder(
"Unexpected reflection exception - ")).append(ex.getClass()
.getName()).append(": ").append(ex.getMessage()).toString());
}
/**
* 处理异常
* @param ex 异常
*/
public void handleInvocationTargetException(InvocationTargetException ex)
{
if (ex.getTargetException() instanceof RuntimeException)
throw (RuntimeException)ex.getTargetException();
if (ex.getTargetException() instanceof Error)
throw (Error)ex.getTargetException();
else
throw new IllegalStateException(
(new StringBuilder(
"Unexpected exception thrown by method - ")).append(ex.getTargetException()
.getClass()
.getName())
.append(": ")
.append(ex.getTargetException().getMessage())
.toString());
}
public boolean isDebugEnable()
{
return debugLogger.isDebugEnabled();
}
public void atCollectionSize(String desc, Collection<?> collection)
{
if (!isDebugEnable())
{
return;
}
try
{
StackTraceElement[] eles = Thread.currentThread().getStackTrace();
int index = getMethodIndex(eles);
String methodName = eles[index].getMethodName();
Integer num = eles[index].getLineNumber();
StringBuffer str = new StringBuffer();
str.append("[");
str.append(Thread.currentThread().hashCode());
str.append("]");
str.append("[----At-------]" + methodName + "." + num + "[Params]");
str.append("( ");
str.append(desc);
str.append("[size]");
str.append("=");
if (null == collection)
{
str.append("null");
}
else
{
str.append(collection.size());
}
str.append(" )");
debugLogger.debug(str.toString());
}
catch (Throwable e)
{
debugLogger.debug("[Exception][Function]atFuncDebugLog[Description]"
+ e.toString());
}
}
}