├── .gitignore ├── CHANGES.txt ├── LICENSE.txt ├── README.md ├── pom.xml └── src ├── main ├── java │ └── com │ │ └── alibaba │ │ └── tamper │ │ ├── BeanCopy.java │ │ ├── BeanMap.java │ │ ├── BeanMapping.java │ │ ├── BeanMappingUtil.java │ │ ├── core │ │ ├── BeanMappingException.java │ │ ├── BeanMappingExecutor.java │ │ ├── BeanMappingParam.java │ │ ├── builder │ │ │ ├── BeanMappingBuilder.java │ │ │ ├── Builder.java │ │ │ └── impl │ │ │ │ ├── BeanMappingBehaviorBuilder.java │ │ │ │ ├── BeanMappingFieldAttributesBuilder.java │ │ │ │ ├── BeanMappingFieldBuilder.java │ │ │ │ └── BeanMappingObjectBuilder.java │ │ ├── config │ │ │ ├── BeanMappingBehavior.java │ │ │ ├── BeanMappingConfigHelper.java │ │ │ ├── BeanMappingConfigRespository.java │ │ │ ├── BeanMappingEnvironment.java │ │ │ ├── BeanMappingField.java │ │ │ ├── BeanMappingFieldAttributes.java │ │ │ ├── BeanMappingObject.java │ │ │ └── parse │ │ │ │ ├── BeanMappingBehaviorParse.java │ │ │ │ ├── BeanMappingParse.java │ │ │ │ ├── BeanMappingParser.java │ │ │ │ ├── ClassAliasParse.java │ │ │ │ ├── ConvertorParse.java │ │ │ │ └── FunctionClassParse.java │ │ ├── helper │ │ │ ├── BatchObjectHolder.java │ │ │ ├── ContextObjectHolder.java │ │ │ ├── ReflectionHelper.java │ │ │ └── XmlHelper.java │ │ ├── introspect │ │ │ ├── AbstractBatchExecutor.java │ │ │ ├── AbstractExecutor.java │ │ │ ├── BatchExecutor.java │ │ │ ├── FastPropertyGetExecutor.java │ │ │ ├── FastPropertySetExecutor.java │ │ │ ├── FieldGetExecutor.java │ │ │ ├── FieldSetExecutor.java │ │ │ ├── GetExecutor.java │ │ │ ├── Introspector.java │ │ │ ├── MapBatchExecutor.java │ │ │ ├── MapGetExecutor.java │ │ │ ├── MapSetExecutor.java │ │ │ ├── NullSymbolGetExecutor.java │ │ │ ├── PropertyBatchExecutor.java │ │ │ ├── PropertyGetExecutor.java │ │ │ ├── PropertySetExecutor.java │ │ │ ├── SetExecutor.java │ │ │ ├── ThisSymbolGetExecutor.java │ │ │ ├── Uberspect.java │ │ │ ├── UberspectImpl.java │ │ │ └── Uberspector.java │ │ └── process │ │ │ ├── ValueProcess.java │ │ │ ├── ValueProcessContext.java │ │ │ └── ValueProcessInvocation.java │ │ └── process │ │ ├── BeanCreatorValueProcess.java │ │ ├── BehaviorValueProcess.java │ │ ├── ConvertorValueProcess.java │ │ ├── DebugValueProcess.java │ │ ├── DefaultValueValueProcess.java │ │ ├── ScriptValueProcess.java │ │ ├── convertor │ │ ├── AbastactConvertor.java │ │ ├── CollectionAndCollectionConvertor.java │ │ ├── CollectionConvertor.java │ │ ├── CommonAndCommonConvertor.java │ │ ├── Convertor.java │ │ ├── ConvertorHelper.java │ │ ├── ConvertorRepository.java │ │ ├── SqlDateAndDateConvertor.java │ │ ├── StringAndCommonConvertor.java │ │ ├── StringAndDateConvertor.java │ │ ├── StringAndEnumConvertor.java │ │ └── StringAndObjectConvertor.java │ │ └── script │ │ ├── ScriptContext.java │ │ ├── ScriptExecutor.java │ │ ├── ScriptHelper.java │ │ ├── jexl │ │ └── JexlScriptExecutor.java │ │ └── lifecyle │ │ ├── DisposableScript.java │ │ └── InitializingScript.java └── resources │ ├── META-INF │ └── mapping.xsd │ └── mapping.properties └── test ├── java └── com │ └── alibaba │ └── tamper │ ├── BeanCopyTest.java │ ├── BeanMapTest.java │ ├── BeanMappingDymaicTest.java │ ├── BeanMappingNestAndNameTest.java │ ├── BeanMappingTest.java │ ├── ConfigTest.java │ ├── InheritObjectMappingTest.java │ ├── TestUtils.java │ ├── builder │ └── BeanMappingBuilderTest.java │ ├── convertor │ ├── CollectionAndCollectionTest.java │ ├── CommonAndCommonTest.java │ ├── ConvertorModel.java │ ├── ConvertorOtherModel.java │ ├── DateAndSqlDateTest.java │ ├── StringAndEnumTest.java │ └── StringConvertorTest.java │ ├── object │ ├── NestedSrcMappingObject.java │ ├── NestedTargetMappingObject.java │ ├── SrcMappingObject.java │ ├── TargetMappingObject.java │ └── inherit │ │ ├── FirstObject.java │ │ └── TwoObject.java │ ├── performace │ ├── AbstractPerformance.java │ ├── CopyBean.java │ ├── CopyPerformance.java │ └── MapPerformance.java │ └── script │ ├── CustomFunctionClass.java │ ├── CustomFunctionTest.java │ ├── ScriptExecutorTest.java │ └── ScriptTest.java └── resources ├── META-INF └── services │ └── BeanMapping.Script.Executor ├── log4j.xml └── mapping ├── config.xml ├── mapping.xml └── script-mapping.xml /.gitignore: -------------------------------------------------------------------------------- 1 | .project 2 | .classpath 3 | target 4 | classes 5 | tmp 6 | temp 7 | *.log* 8 | .settings 9 | antx.properties 10 | test-output 11 | bin 12 | docs 13 | -------------------------------------------------------------------------------- /CHANGES.txt: -------------------------------------------------------------------------------- 1 | Release 1.0.2 2 | convetor包名重构,拼写错误 3 | ScriptExecutor接口重构,加上ScriptContext操作 4 | FiledSetExecutor去除对args的强制匹配依赖 5 | mapping支持name定义 6 | mapping支持嵌套映射/集合映射对象的name定义 7 | 增加NullSymbolGetExecutor的实现,支持无源属性的映射 8 | 9 | Release 1.0.1 10 | "this" symbol GetExecutor bugfix 11 | boolean isSuccessed generated set/get methods for the isSucessed()/setSuccessed(), should filter attribute is the prefix 12 | Add date and sqlDate convertor 13 | Add String and Enum convertor 14 | Add mapping.propertis define ValueProcess plugins 15 | 16 | Release 1.0.0 17 | Initial mapping code 18 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/BeanCopy.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper; 2 | 3 | import com.alibaba.tamper.core.BeanMappingException; 4 | import com.alibaba.tamper.core.BeanMappingExecutor; 5 | import com.alibaba.tamper.core.BeanMappingParam; 6 | import com.alibaba.tamper.core.config.BeanMappingConfigHelper; 7 | import com.alibaba.tamper.core.config.BeanMappingEnvironment; 8 | import com.alibaba.tamper.core.config.BeanMappingObject; 9 | 10 | /** 11 | * Bean copy操作的处理单元 12 | * 13 | *
14 |  * 
15 |  * 使用例子:
16 |  *  BeanCopy beanCopy = BeanCopy.create(srcClass , targetClass);
17 |  *  beanCopy.copy(src,target);//完成copy动作
18 |  * 
19 |  * 
20 | * 21 | * @author jianghang 2011-6-8 上午11:10:47 22 | */ 23 | public class BeanCopy { 24 | 25 | private BeanMappingObject config; // 对应的Bean Mapping配置 26 | 27 | BeanCopy(BeanMappingObject config){ 28 | this.config = config; 29 | } 30 | 31 | /** 32 | * 创建srcClass和targetClass之间的BeanCopy操作 33 | */ 34 | public static BeanCopy create(Class srcClass, Class targetClass) { 35 | BeanMappingObject config = BeanMappingConfigHelper.getInstance().getBeanMappingObject(srcClass, targetClass, 36 | true); 37 | return new BeanCopy(config); 38 | } 39 | 40 | /** 41 | * 对象属性的拷贝,与BeanUtils , BeanCopier功能类似 42 | * 43 | * @param src 44 | * @param target 45 | * @throws BeanMappingException 46 | */ 47 | public void copy(Object src, Object target) throws BeanMappingException { 48 | BeanMappingParam param = new BeanMappingParam(); 49 | param.setSrcRef(src); 50 | param.setTargetRef(target); 51 | param.setConfig(this.config); 52 | param.setProcesses(BeanMappingEnvironment.getBeanCopyVps()); 53 | 54 | // 执行mapping处理 55 | BeanMappingExecutor.execute(param); 56 | } 57 | 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/BeanMap.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import com.alibaba.tamper.core.BeanMappingException; 7 | import com.alibaba.tamper.core.BeanMappingExecutor; 8 | import com.alibaba.tamper.core.BeanMappingParam; 9 | import com.alibaba.tamper.core.config.BeanMappingConfigHelper; 10 | import com.alibaba.tamper.core.config.BeanMappingEnvironment; 11 | import com.alibaba.tamper.core.config.BeanMappingObject; 12 | 13 | /** 14 | * Bean<->Map操作的处理单元 15 | * 16 | *
17 |  * 
18 |  * 使用例子:
19 |  *  BeanMap beanMap = BeanMap.create(srcClass);
20 |  *  Map properties = beanMap.describe(src);// 将bean的属性设置到map对象上
21 |  *  beanMap.populate(src,properties); // 将map对象数据设置到bean的属性上
22 |  * 
23 |  * 
24 | * 25 | * TODO : 后期支持单个属性的put/get操作 26 | * 27 | * @author jianghang 2011-6-8 上午11:11:13 28 | */ 29 | public class BeanMap { 30 | 31 | private BeanMappingObject describeConfig; // 对应的Bean Mapping配置 32 | private BeanMappingObject populateConfig; // 对应的Bean Mapping配置 33 | 34 | BeanMap(BeanMappingObject describeConfig, BeanMappingObject populateConfig){ 35 | this.describeConfig = describeConfig; 36 | this.populateConfig = populateConfig; 37 | } 38 | 39 | /** 40 | * 创建srcClass和targetClass之间的BeanMapping操作 41 | */ 42 | public static BeanMap create(Class srcClass) { 43 | BeanMappingObject describeConfig = BeanMappingConfigHelper.getInstance().getBeanMapObject(srcClass, Map.class, 44 | true); 45 | 46 | BeanMappingObject populateConfig = BeanMappingConfigHelper.getInstance().getBeanMapObject(Map.class, srcClass, 47 | true); 48 | return new BeanMap(describeConfig, populateConfig); 49 | } 50 | 51 | /** 52 | * 将bean的属性转化为Map对象 53 | * 54 | * @param src 55 | * @return 56 | * @throws BeanMappingException 57 | */ 58 | public Map describe(Object src) throws BeanMappingException { 59 | Map result = new HashMap(); 60 | BeanMappingParam param = new BeanMappingParam(); 61 | param.setSrcRef(src); 62 | param.setTargetRef(result); 63 | param.setConfig(this.describeConfig); 64 | param.setProcesses(BeanMappingEnvironment.getBeanMapVps()); 65 | // 执行mapping处理 66 | BeanMappingExecutor.execute(param); 67 | return result; 68 | } 69 | 70 | /** 71 | * 将map的属性映射到bean对象 72 | * 73 | * @param target 74 | * @param properties 75 | * @throws BeanMappingException 76 | */ 77 | public void populate(Object target, Map properties) throws BeanMappingException { 78 | BeanMappingParam param = new BeanMappingParam(); 79 | param.setSrcRef(properties); 80 | param.setTargetRef(target); 81 | param.setConfig(this.populateConfig); 82 | param.setProcesses(BeanMappingEnvironment.getBeanMapVps()); 83 | // 执行mapping处理 84 | BeanMappingExecutor.execute(param); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/BeanMapping.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper; 2 | 3 | import java.util.List; 4 | 5 | import com.alibaba.tamper.core.BeanMappingException; 6 | import com.alibaba.tamper.core.BeanMappingExecutor; 7 | import com.alibaba.tamper.core.BeanMappingParam; 8 | import com.alibaba.tamper.core.builder.BeanMappingBuilder; 9 | import com.alibaba.tamper.core.config.BeanMappingConfigHelper; 10 | import com.alibaba.tamper.core.config.BeanMappingEnvironment; 11 | import com.alibaba.tamper.core.config.BeanMappingObject; 12 | import com.alibaba.tamper.core.helper.ContextObjectHolder; 13 | import com.alibaba.tamper.core.process.ValueProcess; 14 | import com.alibaba.tamper.process.script.ScriptHelper; 15 | 16 | /** 17 | * Bean Mapping操作的处理单元 18 | * 19 | *
 20 |  * 
 21 |  * 使用例子:
 22 |  *  BeanMapping beanMapping = BeanMapping.create(srcClass,targetClass);
 23 |  *  beanMapping.mapping(src,target);// 将src的属性mapping到target
 24 |  *  
 25 |  *  注意:srcClass/targetClass的映射关系必须实现通过{@linkplain BeanMappingConfigHelper}的registerConfig方法注册mapping配置
 26 |  * 
 27 |  * 
 28 |  * changelog
 29 |  *  v1.0.2 
 30 |  *      mapping执行会有context的概念,缓存一下当前的一些执行信息
 31 |  * 
32 | * 33 | * @author jianghang 2011-6-8 上午11:10:24 34 | */ 35 | public class BeanMapping { 36 | 37 | private BeanMappingObject config; // 对应的Bean Mapping配置 38 | 39 | public BeanMapping(BeanMappingObject config){ 40 | this.config = config; 41 | } 42 | 43 | public BeanMapping(BeanMappingBuilder builder){ 44 | this.config = builder.get(); 45 | } 46 | 47 | /** 48 | * 创建指定name的BeanMapping操作 49 | */ 50 | public static BeanMapping create(String mappingName) { 51 | BeanMappingObject config = BeanMappingConfigHelper.getInstance().getBeanMappingObject(mappingName); 52 | if (config == null) { 53 | throw new BeanMappingException("can not found mapping config for name[" + mappingName + "]"); 54 | } 55 | 56 | return new BeanMapping(config); 57 | } 58 | 59 | /** 60 | * 创建srcClass和targetClass之间的BeanMapping操作 61 | */ 62 | public static BeanMapping create(Class srcClass, Class targetClass) { 63 | BeanMappingObject config = BeanMappingConfigHelper.getInstance().getBeanMappingObject(srcClass, targetClass); 64 | if (config == null) { 65 | throw new BeanMappingException("can not found mapping config for srcClass[" + srcClass.toString() 66 | + "] targetClass[" + targetClass + "]"); 67 | } 68 | 69 | return new BeanMapping(config); 70 | } 71 | 72 | /** 73 | * 根据定义的bean-mapping配置进行对象属性的mapping拷贝 , 允许自定义{@linkplain ValueProcess} {@linkplain SetValueProcess} 74 | * 75 | * @param src 76 | * @param target 77 | * @throws BeanMappingException 78 | */ 79 | public void mapping(Object src, Object target) throws BeanMappingException { 80 | boolean first = ContextObjectHolder.getInstance().enter(); 81 | boolean isBeanMappingSupportScript = BeanMappingEnvironment.isBeanMappingSupportScript(); 82 | BeanMappingParam param = new BeanMappingParam(); 83 | param.setSrcRef(src); 84 | param.setTargetRef(target); 85 | param.setConfig(this.config); 86 | List vps = BeanMappingEnvironment.getBeanMappingVps(); 87 | param.setProcesses(vps); 88 | 89 | // 执行mapping处理 90 | try { 91 | BeanMappingExecutor.execute(param); 92 | } finally { 93 | if (first) {// 第一个进入的负责清空数据,可能存在递归调用处理 94 | ContextObjectHolder.getInstance().clear(); 95 | if (isBeanMappingSupportScript) { 96 | ScriptHelper.getInstance().getScriptExecutor().disposeFunctions();// 清空记录 97 | } 98 | } 99 | } 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/BeanMappingUtil.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper; 2 | 3 | import java.util.Map; 4 | 5 | import com.alibaba.tamper.core.BeanMappingException; 6 | 7 | /** 8 | * Bean mapping处理的一些常用方法 9 | * 10 | * @author jianghang 2011-5-27 下午12:27:12 11 | */ 12 | public class BeanMappingUtil { 13 | 14 | /** 15 | * 根据定义的bean-mapping配置进行对象属性的mapping拷贝 16 | * 17 | * @param src 18 | * @param target 19 | */ 20 | public static void mapping(Object src, Object target) throws BeanMappingException { 21 | BeanMapping mapping = BeanMapping.create(src.getClass(), target.getClass()); 22 | mapping.mapping(src, target); 23 | } 24 | 25 | /** 26 | * 对象属性的拷贝,与BeanUtils , BeanCopier功能类似 27 | * 28 | * @param src 29 | * @param target 30 | */ 31 | public static void copy(Object src, Object target) throws BeanMappingException { 32 | BeanCopy copy = BeanCopy.create(src.getClass(), target.getClass()); 33 | copy.copy(src, target); 34 | } 35 | 36 | /** 37 | *将bean的属性转化为Map对象 38 | * 39 | * @param src 40 | * @return 41 | * @throws BeanMappingException 42 | */ 43 | public static Map describe(Object src) throws BeanMappingException { 44 | BeanMap map = BeanMap.create(src.getClass()); 45 | return map.describe(src); 46 | } 47 | 48 | /** 49 | * 将map的属性映射到bean对象 50 | * 51 | * @param target 52 | * @param properties 53 | * @throws BeanMappingException 54 | */ 55 | public static void populate(Object target, Map properties) throws BeanMappingException { 56 | BeanMap map = BeanMap.create(target.getClass()); 57 | map.populate(target, properties); 58 | } 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/BeanMappingException.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core; 2 | 3 | import org.apache.commons.lang.exception.NestableRuntimeException; 4 | 5 | /** 6 | * @author jianghang 2011-5-25 上午11:23:59 7 | */ 8 | public class BeanMappingException extends NestableRuntimeException { 9 | 10 | private static final long serialVersionUID = -4176128184885659405L; 11 | 12 | public BeanMappingException(){ 13 | super(); 14 | } 15 | 16 | public BeanMappingException(String message, Throwable cause){ 17 | super(message, cause); 18 | } 19 | 20 | public BeanMappingException(String message){ 21 | super(message); 22 | } 23 | 24 | public BeanMappingException(Throwable cause){ 25 | super(cause); 26 | } 27 | 28 | } 29 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/BeanMappingParam.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core; 2 | 3 | import java.io.Serializable; 4 | import java.util.HashMap; 5 | import java.util.List; 6 | import java.util.Map; 7 | 8 | import org.apache.commons.lang.builder.ToStringBuilder; 9 | import org.apache.commons.lang.builder.ToStringStyle; 10 | 11 | import com.alibaba.tamper.core.config.BeanMappingObject; 12 | import com.alibaba.tamper.core.process.ValueProcess; 13 | 14 | /** 15 | * bean mapping传递的参数 16 | * 17 | * @author jianghang 2011-5-26 下午06:39:29 18 | */ 19 | public class BeanMappingParam implements Serializable { 20 | 21 | private static final long serialVersionUID = 2371233083866029415L; 22 | private Object srcRef; // 待转化src 23 | private Object targetRef; // 转化的目标dest 24 | private BeanMappingObject config; // bean mapping相关配置 25 | 26 | // =========================== ValueProcess 扩展参数============================== 27 | private List processes; // 自定义的valueProcess 28 | private Map customValueContext = new HashMap(); // 自定义的valueProcess上下文处理 29 | 30 | public Object getSrcRef() { 31 | return srcRef; 32 | } 33 | 34 | public void setSrcRef(Object srcRef) { 35 | this.srcRef = srcRef; 36 | } 37 | 38 | public Object getTargetRef() { 39 | return targetRef; 40 | } 41 | 42 | public void setTargetRef(Object targetRef) { 43 | this.targetRef = targetRef; 44 | } 45 | 46 | public BeanMappingObject getConfig() { 47 | return config; 48 | } 49 | 50 | public void setConfig(BeanMappingObject config) { 51 | this.config = config; 52 | } 53 | 54 | public Map getCustomValueContext() { 55 | return customValueContext; 56 | } 57 | 58 | public void setCustomValueContext(Map customValueContext) { 59 | this.customValueContext = customValueContext; 60 | } 61 | 62 | public List getProcesses() { 63 | return processes; 64 | } 65 | 66 | public void setProcesses(List processes) { 67 | this.processes = processes; 68 | } 69 | 70 | @Override 71 | public String toString() { 72 | return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/builder/BeanMappingBuilder.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.builder; 2 | 3 | import com.alibaba.tamper.core.builder.impl.BeanMappingBehaviorBuilder; 4 | import com.alibaba.tamper.core.builder.impl.BeanMappingFieldAttributesBuilder; 5 | import com.alibaba.tamper.core.builder.impl.BeanMappingFieldBuilder; 6 | import com.alibaba.tamper.core.builder.impl.BeanMappingObjectBuilder; 7 | import com.alibaba.tamper.core.config.BeanMappingBehavior; 8 | import com.alibaba.tamper.core.config.BeanMappingConfigHelper; 9 | import com.alibaba.tamper.core.config.BeanMappingConfigRespository; 10 | import com.alibaba.tamper.core.config.BeanMappingObject; 11 | 12 | /** 13 | * mapping对象的构造器, 可直接注册到{@linkplain BeanMappingConfigRespository} 14 | * 15 | *
16 |  * BeanMappingConfigRespository.register(BeanMappingBuilder);
17 |  * 
18 | * 19 | * @author jianghang 2011-6-22 上午10:31:35 20 | */ 21 | public class BeanMappingBuilder implements Builder { 22 | 23 | private BeanMappingObject object; 24 | private BeanMappingBehavior global = BeanMappingConfigHelper.getInstance().getGlobalBehavior(); 25 | 26 | public BeanMappingBuilder(){ 27 | configure(); 28 | } 29 | 30 | protected void configure() { 31 | // 需要客户端实现 32 | } 33 | 34 | public BeanMappingObjectBuilder mapping(String name, Class srcClass, Class targetClass) { 35 | BeanMappingObjectBuilder builder = new BeanMappingObjectBuilder(name, srcClass, targetClass, global); 36 | object = builder.get(); 37 | return builder; 38 | } 39 | 40 | public BeanMappingObjectBuilder mapping(Class srcClass, Class targetClass) { 41 | BeanMappingObjectBuilder builder = new BeanMappingObjectBuilder(srcClass, targetClass, global); 42 | object = builder.get(); 43 | return builder; 44 | } 45 | 46 | public BeanMappingFieldBuilder fields(BeanMappingFieldAttributesBuilder srcFieldBuilder, 47 | BeanMappingFieldAttributesBuilder targetFieldBuilder) { 48 | BeanMappingFieldBuilder fieldCriterion = new BeanMappingFieldBuilder(srcFieldBuilder, targetFieldBuilder, 49 | this.object.getBehavior()); 50 | this.object.addBeanField(fieldCriterion.get()); 51 | return fieldCriterion; 52 | } 53 | 54 | public BeanMappingBehaviorBuilder behavior() { 55 | BeanMappingBehaviorBuilder builder = new BeanMappingBehaviorBuilder(); 56 | global = builder.get(); 57 | return builder; 58 | 59 | } 60 | 61 | public BeanMappingBehaviorBuilder behavior(boolean debug, boolean mappingNullValue, boolean mappingEmptyStrings, 62 | boolean trimStrings) { 63 | BeanMappingBehaviorBuilder builder = new BeanMappingBehaviorBuilder(debug, mappingNullValue, 64 | mappingEmptyStrings, trimStrings); 65 | global = builder.get(); 66 | return builder; 67 | 68 | } 69 | 70 | public BeanMappingFieldAttributesBuilder srcField(String name) { 71 | return new BeanMappingFieldAttributesBuilder(name); 72 | } 73 | 74 | public BeanMappingFieldAttributesBuilder srcField(String name, Class clazz) { 75 | return new BeanMappingFieldAttributesBuilder(name, clazz); 76 | } 77 | 78 | public BeanMappingFieldAttributesBuilder targetField(String name) { 79 | return new BeanMappingFieldAttributesBuilder(name); 80 | } 81 | 82 | public BeanMappingFieldAttributesBuilder targetField(String name, Class clazz) { 83 | return new BeanMappingFieldAttributesBuilder(name, clazz); 84 | } 85 | 86 | @Override 87 | public BeanMappingObject get() { 88 | return object; 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/builder/Builder.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 1999-2004 Alibaba.com All right reserved. This software is the confidential and proprietary information of 3 | * Alibaba.com ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only 4 | * in accordance with the terms of the license agreement you entered into with Alibaba.com. 5 | */ 6 | package com.alibaba.tamper.core.builder; 7 | 8 | /** 9 | * 定义builder的接口 10 | * 11 | * @author jianghang 2011-6-22 下午12:20:15 12 | */ 13 | public interface Builder { 14 | 15 | public T get(); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/builder/impl/BeanMappingBehaviorBuilder.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.builder.impl; 2 | 3 | import com.alibaba.tamper.core.builder.Builder; 4 | import com.alibaba.tamper.core.config.BeanMappingBehavior; 5 | 6 | /** 7 | * {@linkplain BeanMappingBehavior}构造器 8 | * 9 | * @author jianghang 2011-6-22 下午12:47:50 10 | */ 11 | public class BeanMappingBehaviorBuilder implements Builder { 12 | 13 | private BeanMappingBehavior behavior; 14 | 15 | public BeanMappingBehaviorBuilder(){ 16 | this.behavior = new BeanMappingBehavior(); 17 | } 18 | 19 | public BeanMappingBehaviorBuilder(boolean debug, boolean mappingNullValue, boolean mappingEmptyStrings, 20 | boolean trimStrings){ 21 | this.behavior = new BeanMappingBehavior(); 22 | behavior.setDebug(debug); 23 | behavior.setMappingNullValue(mappingNullValue); 24 | behavior.setMappingEmptyStrings(mappingEmptyStrings); 25 | behavior.setTrimStrings(trimStrings); 26 | } 27 | 28 | public BeanMappingBehaviorBuilder debug(boolean debug) { 29 | behavior.setDebug(debug); 30 | return this; 31 | } 32 | 33 | public BeanMappingBehaviorBuilder mappingNullValue(boolean mappingNullValue) { 34 | behavior.setMappingNullValue(mappingNullValue); 35 | return this; 36 | } 37 | 38 | public BeanMappingBehaviorBuilder mappingEmptyStrings(boolean mappingEmptyStrings) { 39 | behavior.setMappingEmptyStrings(mappingEmptyStrings); 40 | return this; 41 | } 42 | 43 | public BeanMappingBehaviorBuilder trimStrings(boolean trimStrings) { 44 | behavior.setTrimStrings(trimStrings); 45 | return this; 46 | } 47 | 48 | @Override 49 | public BeanMappingBehavior get() { 50 | return behavior; 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/builder/impl/BeanMappingFieldAttributesBuilder.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.builder.impl; 2 | 3 | import java.util.Arrays; 4 | 5 | import com.alibaba.tamper.core.builder.Builder; 6 | import com.alibaba.tamper.core.config.BeanMappingFieldAttributes; 7 | 8 | /** 9 | * {@linkplain BeanMappingFieldAttributes} 构造器 10 | * 11 | * @author jianghang 2011-6-22 上午10:44:13 12 | */ 13 | public class BeanMappingFieldAttributesBuilder implements Builder { 14 | 15 | private BeanMappingFieldAttributes attributes; 16 | 17 | public BeanMappingFieldAttributesBuilder(String name){ 18 | this(name, null); 19 | } 20 | 21 | public BeanMappingFieldAttributesBuilder(String name, Class clazz){ 22 | attributes = new BeanMappingFieldAttributes(); 23 | attributes.setName(name); 24 | attributes.setClazz(clazz); 25 | } 26 | 27 | /** 28 | * 设置属性对应的class对象 29 | */ 30 | public BeanMappingFieldAttributesBuilder clazz(Class clazz) { 31 | attributes.setClazz(clazz); 32 | return this; 33 | } 34 | 35 | /** 36 | * 设置查找对应属性的目标class,默认会以mapping中定义的class进行查找 37 | *

38 | * 针对存在子父属性进行mapping时,可设置此locatorClass进行区分 39 | */ 40 | public BeanMappingFieldAttributesBuilder locatorClass(Class locatorClass) { 41 | attributes.setLocatorClass(locatorClass); 42 | return this; 43 | } 44 | 45 | /** 46 | * 针对Collection的属性,可以设置嵌套的内部对象类型 47 | * 48 | *

49 |      * 针对嵌套处理说明: 比如List<Set<List<Model>>>,
50 |      * 此时对应的componentClasses存在3个Class,分别为Set.class(第一层),List.class(第二层),Model.class(第三层)
51 |      * 
52 |      * 
53 | */ 54 | public BeanMappingFieldAttributesBuilder componentClasses(Class... componentClasses) { 55 | attributes.setComponentClasses(Arrays.asList(componentClasses)); 56 | return this; 57 | } 58 | 59 | public BeanMappingFieldAttributes get() { 60 | return attributes; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/builder/impl/BeanMappingFieldBuilder.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.builder.impl; 2 | 3 | import com.alibaba.tamper.core.builder.BeanMappingBuilder; 4 | import com.alibaba.tamper.core.builder.Builder; 5 | import com.alibaba.tamper.core.config.BeanMappingBehavior; 6 | import com.alibaba.tamper.core.config.BeanMappingField; 7 | 8 | /** 9 | * {@linkplain BeanMappingField}构造器 10 | * 11 | * @author jianghang 2011-6-22 上午10:42:38 12 | */ 13 | public class BeanMappingFieldBuilder implements Builder { 14 | 15 | private BeanMappingField field; 16 | 17 | public BeanMappingFieldBuilder(BeanMappingFieldAttributesBuilder srcField, 18 | BeanMappingFieldAttributesBuilder targetField, BeanMappingBehavior parent){ 19 | this(srcField, targetField, false, parent); 20 | } 21 | 22 | public BeanMappingFieldBuilder(BeanMappingFieldAttributesBuilder srcField, 23 | BeanMappingFieldAttributesBuilder targetField, boolean mapping, 24 | BeanMappingBehavior parent){ 25 | field = new BeanMappingField(); 26 | field.setSrcField(srcField.get()); 27 | field.setTargetField(targetField.get()); 28 | field.setMapping(mapping); 29 | field.setBehavior(parent.clone()); 30 | } 31 | 32 | /** 33 | * 是否打印debug信息 34 | */ 35 | public BeanMappingFieldBuilder debug(boolean debug) { 36 | field.getBehavior().setDebug(debug); 37 | return this; 38 | } 39 | 40 | /** 41 | * 针对null value是否进行mapping set操作 42 | */ 43 | public BeanMappingFieldBuilder mappingNullValue(boolean mappingNullValue) { 44 | field.getBehavior().setMappingNullValue(mappingNullValue); 45 | return this; 46 | } 47 | 48 | /** 49 | * 针对empty String value是否进行mapping set操作 50 | */ 51 | public BeanMappingFieldBuilder mappingEmptyStrings(boolean mappingEmptyStrings) { 52 | field.getBehavior().setMappingEmptyStrings(mappingEmptyStrings); 53 | return this; 54 | } 55 | 56 | /** 57 | * 是否需要进行trim操作 58 | */ 59 | public BeanMappingFieldBuilder trimStrings(boolean trimStrings) { 60 | field.getBehavior().setTrimStrings(trimStrings); 61 | return this; 62 | } 63 | 64 | /** 65 | * 指定使用的Convertor alias 66 | */ 67 | public BeanMappingFieldBuilder convertor(String alias) { 68 | field.setConvertor(alias); 69 | return this; 70 | } 71 | 72 | /** 73 | * 指定使用的Convertor Class 74 | */ 75 | public BeanMappingFieldBuilder convertor(Class convertorClass) { 76 | field.setConvertorClass(convertorClass); 77 | return this; 78 | } 79 | 80 | /** 81 | * 指定使用的script脚本 82 | */ 83 | public BeanMappingFieldBuilder script(String script) { 84 | field.setScript(script); 85 | return this; 86 | } 87 | 88 | /** 89 | * 指定使用的defaultValue 90 | */ 91 | public BeanMappingFieldBuilder defaultValue(String value) { 92 | field.setDefaultValue(value); 93 | return this; 94 | } 95 | 96 | /** 97 | * 设置是否需要进行递归mapping处理 98 | */ 99 | public BeanMappingFieldBuilder recursiveMapping(boolean mapping) { 100 | field.setMapping(mapping); 101 | return this; 102 | } 103 | 104 | /** 105 | * 设置是否需要进行递归mapping处理 106 | */ 107 | public BeanMappingFieldBuilder recursiveMapping(boolean mapping, String nestname) { 108 | field.setMapping(mapping); 109 | field.setNestName(nestname); 110 | return this; 111 | } 112 | 113 | /** 114 | * 设置是进行递归mapping对象的name 115 | */ 116 | public BeanMappingFieldBuilder nestName(String nestname) { 117 | field.setNestName(nestname); 118 | return this; 119 | } 120 | 121 | /** 122 | * 设置是进行递归mapping对象 123 | */ 124 | public BeanMappingFieldBuilder nestObject(BeanMappingBuilder nestBuilder) { 125 | field.setNestObject(nestBuilder.get()); 126 | return this; 127 | } 128 | 129 | public BeanMappingField get() { 130 | return field; 131 | } 132 | 133 | } 134 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/builder/impl/BeanMappingObjectBuilder.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.builder.impl; 2 | 3 | import com.alibaba.tamper.core.builder.Builder; 4 | import com.alibaba.tamper.core.config.BeanMappingBehavior; 5 | import com.alibaba.tamper.core.config.BeanMappingObject; 6 | 7 | /** 8 | * {@linkplain BeanMappingObject}构造器 9 | * 10 | * @author jianghang 2011-6-22 上午10:10:30 11 | */ 12 | public class BeanMappingObjectBuilder implements Builder { 13 | 14 | private static final long serialVersionUID = 358128791476093909L; 15 | 16 | private BeanMappingObject object; 17 | 18 | public BeanMappingObjectBuilder(String name, Class srcClass, Class targetClass, BeanMappingBehavior parent){ 19 | object = new BeanMappingObject(); 20 | object.setName(name); 21 | object.setSrcClass(srcClass); 22 | object.setTargetClass(targetClass); 23 | object.setBehavior(parent.clone()); 24 | } 25 | 26 | public BeanMappingObjectBuilder(Class srcClass, Class targetClass, BeanMappingBehavior parent){ 27 | object = new BeanMappingObject(); 28 | object.setSrcClass(srcClass); 29 | object.setTargetClass(targetClass); 30 | object.setBehavior(parent.clone()); 31 | } 32 | 33 | /** 34 | * 是否打印debug信息 35 | */ 36 | public BeanMappingObjectBuilder debug(boolean debug) { 37 | object.getBehavior().setDebug(debug); 38 | return this; 39 | } 40 | 41 | /** 42 | * 针对null value是否进行mapping set操作 43 | */ 44 | public BeanMappingObjectBuilder mappingNullValue(boolean mappingNullValue) { 45 | object.getBehavior().setMappingNullValue(mappingNullValue); 46 | return this; 47 | } 48 | 49 | /** 50 | * 针对empty String value是否进行mapping set操作 51 | */ 52 | public BeanMappingObjectBuilder mappingEmptyStrings(boolean mappingEmptyStrings) { 53 | object.getBehavior().setMappingEmptyStrings(mappingEmptyStrings); 54 | return this; 55 | } 56 | 57 | /** 58 | * 是否需要进行trim操作 59 | */ 60 | public BeanMappingObjectBuilder trimStrings(boolean trimStrings) { 61 | object.getBehavior().setTrimStrings(trimStrings); 62 | return this; 63 | } 64 | 65 | /** 66 | * 设置是否进行batch优化,默认为true 67 | */ 68 | public BeanMappingObjectBuilder batch(boolean isBatch) { 69 | object.setBatch(isBatch); 70 | return this; 71 | } 72 | 73 | /** 74 | * 设置是否允许反向mapping,默认为false 75 | */ 76 | public BeanMappingObjectBuilder reversable(boolean reversable) { 77 | object.setReversable(reversable); 78 | return this; 79 | } 80 | 81 | /** 82 | * 指定对应的key,用于script中属性获取 83 | */ 84 | public BeanMappingObjectBuilder keys(String srcKey, String targetKey) { 85 | object.setSrcKey(srcKey); 86 | object.setTargetKey(targetKey); 87 | return this; 88 | } 89 | 90 | public BeanMappingObject get() { 91 | return object; 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/config/BeanMappingBehavior.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.config; 2 | 3 | import org.apache.commons.lang.builder.ToStringBuilder; 4 | import org.apache.commons.lang.builder.ToStringStyle; 5 | 6 | /** 7 | * BeanMapping的一些mapping行为参数 8 | * 9 | * @author jianghang 2011-6-13 下午10:27:07 10 | */ 11 | public class BeanMappingBehavior { 12 | 13 | private boolean debug = false; // 是否打印debug信息 14 | private boolean mappingNullValue = true; // 针对nullValue是否需要进行处理 15 | private boolean mappingEmptyStrings = true; // 针对Empty String是否需要进行处理 16 | private boolean trimStrings = false; // 针对String进行trim处理 17 | 18 | public boolean isDebug() { 19 | return debug; 20 | } 21 | 22 | public void setDebug(boolean debug) { 23 | this.debug = debug; 24 | } 25 | 26 | public boolean isMappingNullValue() { 27 | return mappingNullValue; 28 | } 29 | 30 | public void setMappingNullValue(boolean mappingNullValue) { 31 | this.mappingNullValue = mappingNullValue; 32 | } 33 | 34 | public boolean isMappingEmptyStrings() { 35 | return mappingEmptyStrings; 36 | } 37 | 38 | public void setMappingEmptyStrings(boolean mappingEmptyStrings) { 39 | this.mappingEmptyStrings = mappingEmptyStrings; 40 | } 41 | 42 | public boolean isTrimStrings() { 43 | return trimStrings; 44 | } 45 | 46 | public void setTrimStrings(boolean trimStrings) { 47 | this.trimStrings = trimStrings; 48 | } 49 | 50 | public BeanMappingBehavior clone() { 51 | BeanMappingBehavior behavior = new BeanMappingBehavior(); 52 | behavior.setDebug(this.debug); 53 | behavior.setMappingEmptyStrings(this.mappingEmptyStrings); 54 | behavior.setMappingNullValue(this.mappingNullValue); 55 | behavior.setTrimStrings(this.trimStrings); 56 | return behavior; 57 | } 58 | 59 | @Override 60 | public String toString() { 61 | return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/config/BeanMappingConfigHelper.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.config; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.util.Map; 6 | 7 | import com.alibaba.tamper.core.builder.BeanMappingBuilder; 8 | 9 | /** 10 | * Bean Mapping配置操作的相关helper类 11 | * 12 | * @author jianghang 2011-5-28 上午11:00:34 13 | */ 14 | public class BeanMappingConfigHelper { 15 | 16 | private static volatile BeanMappingConfigHelper singleton = null; 17 | private BeanMappingConfigRespository repository = null; // 基于文件的配置 18 | private BeanMappingConfigRespository autoRepository = null; // 自动注册的配置 19 | private volatile BeanMappingBehavior globalBehavior = null; // 定义为voolatile,允许动态修改 20 | 21 | public BeanMappingConfigHelper(){ 22 | repository = new BeanMappingConfigRespository(); 23 | autoRepository = new BeanMappingConfigRespository(); 24 | globalBehavior = new BeanMappingBehavior(); 25 | } 26 | 27 | public BeanMappingConfigHelper(BeanMappingConfigRespository repository){ 28 | // 允许传入自定义仓库 29 | this.repository = repository; 30 | autoRepository = new BeanMappingConfigRespository(); 31 | globalBehavior = new BeanMappingBehavior(); 32 | } 33 | 34 | /** 35 | * 单例方法 36 | */ 37 | public static BeanMappingConfigHelper getInstance() { 38 | if (singleton == null) { 39 | synchronized (BeanMappingConfigHelper.class) { 40 | if (singleton == null) { // double check 41 | singleton = new BeanMappingConfigHelper(); 42 | } 43 | } 44 | } 45 | return singleton; 46 | } 47 | 48 | /** 49 | * 根据class查找对应的{@linkplain BeanMappingObject} 50 | */ 51 | public BeanMappingObject getBeanMappingObject(Class src, Class target) { 52 | return getFromRepository(src, target, this.repository); 53 | } 54 | 55 | /** 56 | * 根据name查找对应的{@linkplain BeanMappingObject} 57 | */ 58 | public BeanMappingObject getBeanMappingObject(String name) { 59 | return repository.getBeanMappingObject(name); 60 | } 61 | 62 | /** 63 | * 根据class查找对应的{@linkplain BeanMappingObject},如果不存在则进行自动注册 64 | */ 65 | public BeanMappingObject getBeanMappingObject(Class src, Class target, boolean autoRegister) { 66 | BeanMappingObject object = autoRepository.getBeanMappingObject(src, target); 67 | if (object == null && autoRegister) { 68 | autoRepository.register(src, target); 69 | object = getFromRepository(src, target, this.autoRepository); 70 | } 71 | return object; 72 | } 73 | 74 | /** 75 | * 根据class查找对应的{@linkplain BeanMappingObject},如果不存在则进行自动注册 76 | */ 77 | public BeanMappingObject getBeanMapObject(Class src, Class target, boolean autoRegister) { 78 | BeanMappingObject object = autoRepository.getBeanMappingObject(src, target); 79 | if (object == null && autoRegister) { 80 | if (isMap(src)) {// 判断是否为map接口的子类 81 | autoRepository.registerMap(target); 82 | } else { 83 | autoRepository.registerMap(src); 84 | } 85 | 86 | object = getFromRepository(src, target, this.autoRepository); 87 | } 88 | return object; 89 | } 90 | 91 | /** 92 | * 直接注册一个解析好的{@linkplain BeanMappingObject} 93 | */ 94 | public void register(BeanMappingObject object) { 95 | repository.register(object); 96 | } 97 | 98 | /** 99 | * 直接注册一个解析好的{@linkplain BeanMappingBuilder} 100 | */ 101 | public void register(BeanMappingBuilder builder) { 102 | repository.register(builder); 103 | } 104 | 105 | public void registerConfig(String file) { 106 | InputStream in = null; 107 | ClassLoader cl = Thread.currentThread().getContextClassLoader(); 108 | if (cl == null) { 109 | cl = BeanMappingConfigRespository.class.getClassLoader(); 110 | } 111 | in = cl.getResourceAsStream(file); 112 | // 自己打开的文件需要关闭 113 | try { 114 | repository.registerConfig(in); 115 | } finally { 116 | if (in != null) { 117 | try { 118 | in.close(); 119 | } catch (IOException e) { 120 | // ignore 121 | } 122 | } 123 | } 124 | } 125 | 126 | public void registerConfig(InputStream in) { 127 | repository.registerConfig(in); 128 | } 129 | 130 | // ======================== helper method ====================== 131 | 132 | /** 133 | * @param src 134 | * @param target 135 | * @return 136 | */ 137 | private BeanMappingObject getFromRepository(Class src, Class target, BeanMappingConfigRespository repository) { 138 | BeanMappingObject object = repository.getBeanMappingObject(src, target); 139 | if (object == null) { // 再尝试一下map接口的处理 140 | boolean isSrcMap = isMap(src); 141 | boolean isTargetMap = isMap(target); 142 | if (isSrcMap && isTargetMap) { 143 | object = repository.getBeanMappingObject(Map.class, Map.class); 144 | } else if (isSrcMap) { 145 | object = repository.getBeanMappingObject(Map.class, target); 146 | } else if (isMap(target)) { 147 | object = repository.getBeanMappingObject(src, Map.class); 148 | } 149 | } 150 | 151 | return object; 152 | } 153 | 154 | private boolean isMap(Class clazz) { 155 | return clazz != null && Map.class.isAssignableFrom(clazz); 156 | } 157 | 158 | // ========================= setter / getter =================== 159 | 160 | public void setRepository(BeanMappingConfigRespository repository) { 161 | this.repository = repository; 162 | } 163 | 164 | public BeanMappingBehavior getGlobalBehavior() { 165 | return globalBehavior; 166 | } 167 | 168 | public void setGlobalBehavior(BeanMappingBehavior globalBehavior) { 169 | this.globalBehavior = globalBehavior; 170 | } 171 | 172 | } 173 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/config/BeanMappingConfigRespository.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.config; 2 | 3 | import java.io.InputStream; 4 | import java.util.List; 5 | import java.util.Map; 6 | import java.util.concurrent.ConcurrentHashMap; 7 | 8 | import org.apache.commons.lang.StringUtils; 9 | import org.slf4j.Logger; 10 | import org.slf4j.LoggerFactory; 11 | 12 | import com.alibaba.tamper.core.builder.BeanMappingBuilder; 13 | import com.alibaba.tamper.core.config.parse.BeanMappingParser; 14 | 15 | /** 16 | * BeanMappingObject对应的仓库,解析一次Object后会进行cache 17 | * 18 | * @author jianghang 2011-5-26 下午07:57:33 19 | */ 20 | public class BeanMappingConfigRespository { 21 | 22 | private final static Logger logger = LoggerFactory.getLogger(BeanMappingConfigRespository.class); 23 | private static final String SEPERATOR = ":"; 24 | private Map mappings = new ConcurrentHashMap(10); 25 | 26 | /** 27 | * 根据class查找对应的{@linkplain BeanMappingObject} 28 | */ 29 | public BeanMappingObject getBeanMappingObject(Class src, Class target) { 30 | return mappings.get(mapperObjectName(src, target)); 31 | } 32 | 33 | /** 34 | * 根据name查找对应的{@linkplain BeanMappingObject} 35 | */ 36 | public BeanMappingObject getBeanMappingObject(String name) { 37 | return mappings.get(name); 38 | } 39 | 40 | /** 41 | * 直接注册一个解析好的{@linkplain BeanMappingBuilder} 42 | */ 43 | public void register(BeanMappingBuilder builder) { 44 | if (builder != null) { 45 | BeanMappingObject object = builder.get(); 46 | register(object); 47 | } 48 | } 49 | 50 | /** 51 | * 直接注册一个解析号的{@linkplain BeanMappingObject} 52 | */ 53 | public void register(BeanMappingObject object) { 54 | BeanMappingObject old = null; 55 | String name = null; 56 | if (object != null) { 57 | if (StringUtils.isEmpty(object.getName())) { 58 | name = mapperObjectName(object.getSrcClass(), object.getTargetClass()); 59 | } else { 60 | name = object.getName(); 61 | } 62 | 63 | old = mappings.put(name, object); 64 | } 65 | 66 | if (old != null) { 67 | logger.warn("{} has been replaced by : {}", name, object.toString()); 68 | } 69 | } 70 | 71 | /** 72 | * 直接注册为默认mapping 73 | * 74 | * @param src 75 | * @param dest 76 | */ 77 | public void register(Class src, Class target) { 78 | List objects = BeanMappingParser.parseMapping(src, target); 79 | for (BeanMappingObject object : objects) { 80 | register(object); 81 | } 82 | } 83 | 84 | /** 85 | * 直接注册bean和map的mapping关系 86 | */ 87 | public void registerMap(Class src) { 88 | List objects = BeanMappingParser.parseMapMapping(src); 89 | for (BeanMappingObject object : objects) { 90 | register(object); 91 | } 92 | } 93 | 94 | /** 95 | * 注册beanMapping配置的流 96 | */ 97 | public void registerConfig(InputStream in) { 98 | List objects = BeanMappingParser.parseMapping(in); 99 | for (BeanMappingObject object : objects) { 100 | register(object); 101 | } 102 | } 103 | 104 | // ==========================helper method ========================= 105 | 106 | private String mapperObjectName(Class src, Class dest) { 107 | String name1 = src.getName(); 108 | String name2 = dest.getName(); 109 | 110 | return name1 + SEPERATOR + name2; 111 | } 112 | 113 | } 114 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/config/BeanMappingEnvironment.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.config; 2 | 3 | import java.io.IOException; 4 | import java.io.InputStream; 5 | import java.util.ArrayList; 6 | import java.util.List; 7 | import java.util.Properties; 8 | 9 | import org.apache.commons.lang.StringUtils; 10 | 11 | import com.alibaba.tamper.core.BeanMappingException; 12 | import com.alibaba.tamper.core.helper.ReflectionHelper; 13 | import com.alibaba.tamper.core.introspect.Uberspect; 14 | import com.alibaba.tamper.core.introspect.UberspectImpl; 15 | import com.alibaba.tamper.core.process.ValueProcess; 16 | 17 | /** 18 | * mapping的一些环境变量配置 19 | * 20 | * @author jianghang 2012-1-30 下午03:59:21 21 | */ 22 | public class BeanMappingEnvironment { 23 | 24 | private static final String config = "mapping.properties"; 25 | private static final String BEANMAP_VPS = "beanMap.valueProcess.list"; 26 | private static final String BEANMAPPING_VPS = "beanMapping.valueProcess.list"; 27 | private static final String BEANCOPY_VPS = "beanCopy.valueProcess.list"; 28 | 29 | private static final String VALUEPROCESS_PREFIX = "valueProcess."; 30 | private static final String UBERSPECTOR_IMPL = "uberspect.impl"; 31 | 32 | private static Properties properties = new Properties(System.getProperties()); 33 | private static List beanMappingVps; 34 | private static List beanMapVps; 35 | private static List beanCopyVps; 36 | private static Class uberspectClazz; 37 | private static boolean isBeanMappingSupportScript = false; 38 | 39 | static { 40 | InputStream stream = Thread.currentThread().getContextClassLoader().getResourceAsStream(config); 41 | try { 42 | properties.load(stream); 43 | } catch (IOException e) { 44 | throw new BeanMappingException("can't found " + config); 45 | } 46 | try { 47 | // 解析value process 48 | String vps = properties.getProperty(BEANMAPPING_VPS, StringUtils.EMPTY); 49 | beanMappingVps = parseVps(vps); 50 | isBeanMappingSupportScript = StringUtils.containsIgnoreCase(vps, "script"); 51 | 52 | beanMapVps = parseVps(properties.getProperty(BEANMAP_VPS, StringUtils.EMPTY)); 53 | beanCopyVps = parseVps(properties.getProperty(BEANCOPY_VPS, StringUtils.EMPTY)); 54 | // 解析uberspect 55 | String uberspectClazzName = properties.getProperty(UBERSPECTOR_IMPL, UberspectImpl.class.getName()); 56 | uberspectClazz = Class.forName(uberspectClazzName); 57 | } catch (Exception e) { 58 | throw new BeanMappingException(e); 59 | } 60 | } 61 | 62 | public static boolean isBeanMappingSupportScript() { 63 | return isBeanMappingSupportScript; 64 | } 65 | 66 | public static List getBeanMappingVps() { 67 | return beanMappingVps; 68 | } 69 | 70 | public static List getBeanMapVps() { 71 | return beanMapVps; 72 | } 73 | 74 | public static List getBeanCopyVps() { 75 | return beanCopyVps; 76 | } 77 | 78 | public static Uberspect getUberspect() { 79 | return (Uberspect) ReflectionHelper.newInstance(uberspectClazz); 80 | } 81 | 82 | public static void setBeanMappingVps(String vps) { 83 | beanMappingVps = parseVps(vps); 84 | isBeanMappingSupportScript = StringUtils.containsIgnoreCase(vps, "script"); 85 | } 86 | 87 | public static void setBeanMapVps(String vps) { 88 | beanMapVps = parseVps(vps); 89 | } 90 | 91 | public static void setBeanCopyVps(String vps) { 92 | beanCopyVps = parseVps(vps); 93 | } 94 | 95 | public static void setValueProcess(String vp, Class clazz) { 96 | properties.put(vp, clazz.getName()); 97 | } 98 | 99 | public static void setUberspect(Class uberspectClazz) { 100 | BeanMappingEnvironment.uberspectClazz = uberspectClazz; 101 | } 102 | 103 | // =================== help method ======================= 104 | 105 | private static List parseVps(String vps) { 106 | String[] strs = StringUtils.split(vps, ","); 107 | List result = new ArrayList(); 108 | for (String str : strs) { 109 | result.add(initValueProcess(str)); 110 | } 111 | 112 | return result; 113 | } 114 | 115 | private static ValueProcess initValueProcess(String name) { 116 | String className = (String) properties.get(VALUEPROCESS_PREFIX + name); 117 | try { 118 | Class clazz = Class.forName(className); 119 | if (ValueProcess.class.isAssignableFrom(clazz) == false) { 120 | throw new BeanMappingException(className + " is not assign From ValueProcess!"); 121 | } 122 | 123 | return (ValueProcess) ReflectionHelper.newInstance(clazz); 124 | } catch (ClassNotFoundException e) { 125 | throw new BeanMappingException(e); 126 | } 127 | } 128 | 129 | } 130 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/config/BeanMappingField.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.config; 2 | 3 | import java.io.Serializable; 4 | 5 | import org.apache.commons.lang.builder.ToStringBuilder; 6 | import org.apache.commons.lang.builder.ToStringStyle; 7 | 8 | import com.alibaba.tamper.core.introspect.GetExecutor; 9 | import com.alibaba.tamper.core.introspect.SetExecutor; 10 | import com.alibaba.tamper.process.convertor.Convertor; 11 | 12 | /** 13 | * 解析完成后的一个BeanMapping的field配置对象 14 | * 15 | *
 16 |  * changeLog 
 17 |  *  v1.0.2 
 18 |  *      两种条件满足时可以触发使用nestObject对象
 19 |  *      a. mapping=true,需要进行递归映射,会读取nestObject定义的映射规则
 20 |  *      b. 针对field为collection类型,需要进行循环映射,会读取nestObject定义的映射规则
 21 |  * 
22 | * 23 | * @author jianghang 2011-5-23 下午04:25:06 24 | */ 25 | public class BeanMappingField implements Serializable { 26 | 27 | private static final long serialVersionUID = 3673414855182044438L; 28 | private BeanMappingFieldAttributes srcField = new BeanMappingFieldAttributes(); // 源属性配置信息 29 | private BeanMappingFieldAttributes targetField = new BeanMappingFieldAttributes(); // 目标属性配置信息 30 | private String defaultValue = null; // 默认值,配置文件中定义的字符串 31 | private String convertor = null; // 自定义conveterName 32 | private Class convertorClass = null; // 指定convertor的class 33 | private String script = null; // format script字符串 34 | private boolean mapping = false; // 是否深度递归mapping 35 | private String nestName = null; // 定义嵌套映射的名字 36 | private BeanMappingBehavior behavior = null; // mapping的处理行为参数 37 | 38 | // ======================= 内部数据,外部请勿直接操作 ================== 39 | private BeanMappingObject nestObject = null; // 定义嵌套的配置 40 | private Convertor convertorRef = null; // convertor对应的对象引用 41 | private GetExecutor getExecutor = null; // get操作的执行引擎 42 | private SetExecutor setExecutor = null; // set操作的执行引擎 43 | 44 | public String getDefaultValue() { 45 | return defaultValue; 46 | } 47 | 48 | public void setDefaultValue(String defaultValue) { 49 | this.defaultValue = defaultValue; 50 | } 51 | 52 | public String getConvertor() { 53 | return convertor; 54 | } 55 | 56 | public void setConvertor(String convertor) { 57 | this.convertor = convertor; 58 | } 59 | 60 | public String getScript() { 61 | return script; 62 | } 63 | 64 | public void setScript(String script) { 65 | this.script = script; 66 | } 67 | 68 | public boolean isMapping() { 69 | return mapping; 70 | } 71 | 72 | public void setMapping(boolean mapping) { 73 | this.mapping = mapping; 74 | } 75 | 76 | public Class getConvertorClass() { 77 | return convertorClass; 78 | } 79 | 80 | public void setConvertorClass(Class convertorClass) { 81 | this.convertorClass = convertorClass; 82 | } 83 | 84 | public Convertor getConvertorRef() { 85 | return convertorRef; 86 | } 87 | 88 | public void setConvertorRef(Convertor convertorRef) { 89 | this.convertorRef = convertorRef; 90 | } 91 | 92 | public BeanMappingBehavior getBehavior() { 93 | return behavior; 94 | } 95 | 96 | public void setBehavior(BeanMappingBehavior behavior) { 97 | this.behavior = behavior; 98 | } 99 | 100 | public GetExecutor getGetExecutor() { 101 | return getExecutor; 102 | } 103 | 104 | public void setGetExecutor(GetExecutor getExecutor) { 105 | this.getExecutor = getExecutor; 106 | } 107 | 108 | public SetExecutor getSetExecutor() { 109 | return setExecutor; 110 | } 111 | 112 | public void setSetExecutor(SetExecutor setExecutor) { 113 | this.setExecutor = setExecutor; 114 | } 115 | 116 | public BeanMappingFieldAttributes getSrcField() { 117 | return srcField; 118 | } 119 | 120 | public void setSrcField(BeanMappingFieldAttributes srcField) { 121 | this.srcField = srcField; 122 | } 123 | 124 | public BeanMappingFieldAttributes getTargetField() { 125 | return targetField; 126 | } 127 | 128 | public void setTargetField(BeanMappingFieldAttributes targetField) { 129 | this.targetField = targetField; 130 | } 131 | 132 | public BeanMappingObject getNestObject() { 133 | return nestObject; 134 | } 135 | 136 | public void setNestObject(BeanMappingObject nestObject) { 137 | this.nestObject = nestObject; 138 | } 139 | 140 | public String getNestName() { 141 | return nestName; 142 | } 143 | 144 | public void setNestName(String nestName) { 145 | this.nestName = nestName; 146 | } 147 | 148 | @Override 149 | public String toString() { 150 | return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/config/BeanMappingFieldAttributes.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.config; 2 | 3 | import java.io.Serializable; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | import org.apache.commons.lang.builder.ToStringBuilder; 8 | import org.apache.commons.lang.builder.ToStringStyle; 9 | 10 | /** 11 | * mapping配置的field信息配置 12 | * 13 | * @author jianghang 2011-6-21 上午11:32:56 14 | */ 15 | public class BeanMappingFieldAttributes implements Serializable { 16 | 17 | private static final long serialVersionUID = -4833554213883478310L; 18 | private Class locatorClass; // 指定在该LocatorClass,查找对应的目标数据name的属性方法,解决继承属性 19 | private String name; // 源数据的name 20 | private Class clazz; // 源数据的class 21 | 22 | // 允许出现嵌套数组,比如List>>, 23 | // 此时对应的componentClasses存在3个Class,分别为Set.class(第一层),List.class(第二层),Model.class(第三层) 24 | private List componentClasses; // 指定Collection/Array的ComponentType 25 | 26 | public Class getLocatorClass() { 27 | return locatorClass; 28 | } 29 | 30 | public void setLocatorClass(Class locatorClass) { 31 | this.locatorClass = locatorClass; 32 | } 33 | 34 | public String getName() { 35 | return name; 36 | } 37 | 38 | public void setName(String name) { 39 | this.name = name; 40 | } 41 | 42 | public Class getClazz() { 43 | return clazz; 44 | } 45 | 46 | public void setClazz(Class clazz) { 47 | this.clazz = clazz; 48 | } 49 | 50 | public List getComponentClasses() { 51 | return componentClasses; 52 | } 53 | 54 | public void setComponentClasses(List componentClasses) { 55 | this.componentClasses = componentClasses; 56 | } 57 | 58 | public void addComponentClasses(Class componentClass) { 59 | if (componentClasses == null) { 60 | componentClasses = new ArrayList(); 61 | } 62 | 63 | componentClasses.add(componentClass); 64 | } 65 | 66 | @Override 67 | public String toString() { 68 | return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); 69 | } 70 | 71 | } 72 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/config/BeanMappingObject.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.config; 2 | 3 | import java.io.Serializable; 4 | import java.util.ArrayList; 5 | import java.util.List; 6 | 7 | import org.apache.commons.lang.builder.ToStringBuilder; 8 | import org.apache.commons.lang.builder.ToStringStyle; 9 | 10 | import com.alibaba.tamper.core.introspect.BatchExecutor; 11 | 12 | /** 13 | * 解析完成后的一个BeanMapping配置对象 14 | * 15 | *
 16 |  * ChangeLog :
 17 |  * a. 1.0.2支持mapping定义alias name,用于解决map<->map对象的多种映射定义
 18 |  * 
19 | * 20 | * @author jianghang 2011-5-26 下午07:16:10 21 | */ 22 | public class BeanMappingObject implements Serializable { 23 | 24 | private static final long serialVersionUID = 9099474060890980056L; 25 | private String name; // 定义mapping配置name,默认为srcClass:targetClass 26 | private String srcKey = "src"; // format上下文中src key,默认:src 27 | private Class srcClass = null; // mapping的原始class 28 | private String targetKey = "target"; // format上下文中targetkey,默认:target 29 | private Class targetClass = null; // mapping的目标class 30 | private boolean reversable = true; // 原始和目标的mapping是否可逆,如果有自定义的convertor,强制修改为不可逆 31 | private List beanFields = new ArrayList(); // 具体字段的mapping配置 32 | private boolean batch = false; // 优化参数,是否开启批量处理操作. 33 | private BeanMappingBehavior behavior = null; // mapping的处理行为参数 34 | 35 | // ======================= 内部数据,外部请勿直接操作 ================== 36 | private BatchExecutor getBatchExecutor = null; // get操作的batch执行引擎 37 | private BatchExecutor setBatchExecutor = null; // set操作的batch执行引擎 38 | 39 | public String getName() { 40 | return name; 41 | } 42 | 43 | public void setName(String name) { 44 | this.name = name; 45 | } 46 | 47 | public Class getSrcClass() { 48 | return srcClass; 49 | } 50 | 51 | public void setSrcClass(Class srcClass) { 52 | this.srcClass = srcClass; 53 | } 54 | 55 | public Class getTargetClass() { 56 | return targetClass; 57 | } 58 | 59 | public void setTargetClass(Class targetClass) { 60 | this.targetClass = targetClass; 61 | } 62 | 63 | public boolean isReversable() { 64 | return reversable; 65 | } 66 | 67 | public void setReversable(boolean reversable) { 68 | this.reversable = reversable; 69 | } 70 | 71 | public List getBeanFields() { 72 | return beanFields; 73 | } 74 | 75 | public void setBeanFields(List beanFields) { 76 | this.beanFields = beanFields; 77 | } 78 | 79 | public void addBeanField(BeanMappingField beanField) { 80 | if (beanFields == null) { 81 | beanFields = new ArrayList(); 82 | } 83 | 84 | beanFields.add(beanField); 85 | } 86 | 87 | public String getSrcKey() { 88 | return srcKey; 89 | } 90 | 91 | public void setSrcKey(String srcKey) { 92 | this.srcKey = srcKey; 93 | } 94 | 95 | public String getTargetKey() { 96 | return targetKey; 97 | } 98 | 99 | public void setTargetKey(String targetKey) { 100 | this.targetKey = targetKey; 101 | } 102 | 103 | public boolean isBatch() { 104 | return batch; 105 | } 106 | 107 | public void setBatch(boolean batch) { 108 | this.batch = batch; 109 | } 110 | 111 | public BatchExecutor getGetBatchExecutor() { 112 | return getBatchExecutor; 113 | } 114 | 115 | public void setGetBatchExecutor(BatchExecutor getBatchExecutor) { 116 | this.getBatchExecutor = getBatchExecutor; 117 | } 118 | 119 | public BatchExecutor getSetBatchExecutor() { 120 | return setBatchExecutor; 121 | } 122 | 123 | public void setSetBatchExecutor(BatchExecutor setBatchExecutor) { 124 | this.setBatchExecutor = setBatchExecutor; 125 | } 126 | 127 | public BeanMappingBehavior getBehavior() { 128 | return behavior; 129 | } 130 | 131 | public void setBehavior(BeanMappingBehavior behavior) { 132 | this.behavior = behavior; 133 | } 134 | 135 | @Override 136 | public String toString() { 137 | return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE); 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/config/parse/BeanMappingBehaviorParse.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.config.parse; 2 | 3 | import org.w3c.dom.Node; 4 | 5 | import com.alibaba.tamper.core.config.BeanMappingBehavior; 6 | 7 | /** 8 | * 解析下Beahvior相关配置 9 | * 10 | * @author jianghang 2011-6-21 下午01:28:28 11 | */ 12 | public class BeanMappingBehaviorParse { 13 | 14 | public static BeanMappingBehavior parse(Node node, BeanMappingBehavior parent) { 15 | Node debug = node.getAttributes().getNamedItem("debug"); 16 | Node mappingNullValue = node.getAttributes().getNamedItem("mappingNullValue"); 17 | Node mappingEmptyStrings = node.getAttributes().getNamedItem("mappingEmptyStrings"); 18 | Node trimStrings = node.getAttributes().getNamedItem("trimStrings"); 19 | 20 | boolean isConfig = false; 21 | BeanMappingBehavior behavior = parent.clone();// 从上一个节点复制配置,进行替换处理 22 | 23 | if (debug != null) { 24 | behavior.setDebug(Boolean.valueOf(debug.getNodeValue())); 25 | isConfig = true; 26 | } 27 | if (mappingNullValue != null) { 28 | behavior.setMappingNullValue(Boolean.valueOf(mappingNullValue.getNodeValue())); 29 | isConfig = true; 30 | } 31 | if (mappingEmptyStrings != null) { 32 | behavior.setMappingEmptyStrings(Boolean.valueOf(mappingEmptyStrings.getNodeValue())); 33 | isConfig = true; 34 | } 35 | if (trimStrings != null) { 36 | behavior.setTrimStrings(Boolean.valueOf(trimStrings.getNodeValue())); 37 | isConfig = true; 38 | } 39 | 40 | return isConfig ? behavior : parent;// 如果未设置,则直接使用parent 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/config/parse/ClassAliasParse.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.config.parse; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.w3c.dom.Node; 6 | import org.w3c.dom.NodeList; 7 | 8 | import com.alibaba.tamper.core.BeanMappingException; 9 | import com.alibaba.tamper.core.helper.ReflectionHelper; 10 | 11 | /** 12 | * 解析下Class alias的相关配置 13 | * 14 | * @author jianghang 2011-6-21 下午01:33:28 15 | */ 16 | public class ClassAliasParse { 17 | 18 | private final static Logger logger = LoggerFactory.getLogger(ClassAliasParse.class); 19 | 20 | public static void parseAndRegister(Node node) { 21 | NodeList nodeList = node.getChildNodes(); 22 | for (int i = 0; i < nodeList.getLength(); i++) { 23 | Node aliasClassNode = nodeList.item(i); 24 | if ("classAlias".equals(aliasClassNode.getNodeName())) { 25 | Node aliasNode = aliasClassNode.getAttributes().getNamedItem("alias"); 26 | Node clazzNode = aliasClassNode.getAttributes().getNamedItem("class"); 27 | if (aliasNode == null || clazzNode == null) { 28 | throw new BeanMappingException("alias or class is null , please check!"); 29 | } 30 | 31 | String alias = aliasNode.getNodeValue(); 32 | Class clazz = ReflectionHelper.forName(clazzNode.getNodeValue()); 33 | ReflectionHelper.registerClassAlias(aliasNode.getNodeValue(), clazz); 34 | if (logger.isDebugEnabled()) { 35 | logger.debug("register class[" + clazz.toString() + "] to alias[" + alias + "]"); 36 | } 37 | } 38 | } 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/config/parse/ConvertorParse.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.config.parse; 2 | 3 | import org.apache.commons.lang.StringUtils; 4 | import org.slf4j.Logger; 5 | import org.slf4j.LoggerFactory; 6 | import org.w3c.dom.Node; 7 | import org.w3c.dom.NodeList; 8 | 9 | import com.alibaba.tamper.core.BeanMappingException; 10 | import com.alibaba.tamper.core.helper.ReflectionHelper; 11 | import com.alibaba.tamper.process.convertor.Convertor; 12 | import com.alibaba.tamper.process.convertor.ConvertorHelper; 13 | 14 | /** 15 | * 解析下Convertor的相关配置,直接注册到仓库 16 | * 17 | * @author jianghang 2011-6-21 下午01:33:38 18 | */ 19 | public class ConvertorParse { 20 | 21 | private final static Logger logger = LoggerFactory.getLogger(ConvertorParse.class); 22 | 23 | public static void parseAndRegister(Node convertorsNode) { 24 | NodeList nodeList = convertorsNode.getChildNodes(); 25 | for (int i = 0; i < nodeList.getLength(); i++) { 26 | Node node = nodeList.item(i); 27 | if ("convertor".equals(node.getNodeName())) { 28 | Node aliasNode = node.getAttributes().getNamedItem("alias"); 29 | Node clazzNode = node.getAttributes().getNamedItem("class"); 30 | Node srcClassNode = node.getAttributes().getNamedItem("srcClass"); 31 | Node targetClassNode = node.getAttributes().getNamedItem("targetClass"); 32 | if (clazzNode != null) { 33 | Class clazz = ReflectionHelper.forName(clazzNode.getNodeValue()); 34 | if (!Convertor.class.isAssignableFrom(clazz)) { // 检查下必须为Convertor的子类 35 | throw new BeanMappingException(clazz.toString() + " is not implements Convertor"); 36 | } 37 | 38 | Convertor convertor = (Convertor) ReflectionHelper.newInstance(clazz); 39 | if (aliasNode != null) { 40 | // 注册为别名 41 | String alias = aliasNode.getNodeValue(); 42 | ConvertorHelper.getInstance().registerConvertor(alias, convertor); 43 | 44 | if (logger.isDebugEnabled()) { 45 | logger.debug("register Convertor[" + clazz.toString() + "] to alias[" + alias + "]"); 46 | } 47 | } else { 48 | String srcClass = srcClassNode.getNodeValue(); 49 | String targetClass = targetClassNode.getNodeValue(); 50 | if (StringUtils.isEmpty(srcClass) || StringUtils.isEmpty(targetClass)) { 51 | throw new BeanMappingException(clazz.toString() + " should fix srcClass and targetClass!"); 52 | } 53 | Class srcClazz = ReflectionHelper.forName(srcClassNode.getNodeValue()); 54 | Class targetClazz = ReflectionHelper.forName(targetClassNode.getNodeValue()); 55 | // 根据srcClass/targetClass进行自动匹配 56 | ConvertorHelper.getInstance().registerConvertor(srcClazz, targetClazz, convertor); 57 | if (logger.isDebugEnabled()) { 58 | logger.debug("register Convertor[" + clazz.toString() + "] used by srcClass[" 59 | + srcClass.toString() + "]" + " targetClass[" + targetClass.toString() + "]"); 60 | } 61 | } 62 | } 63 | } 64 | } 65 | } 66 | } 67 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/config/parse/FunctionClassParse.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.config.parse; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | import org.w3c.dom.Node; 6 | import org.w3c.dom.NodeList; 7 | 8 | import com.alibaba.tamper.core.BeanMappingException; 9 | import com.alibaba.tamper.core.helper.ReflectionHelper; 10 | import com.alibaba.tamper.process.script.ScriptHelper; 11 | 12 | /** 13 | * 解析下Function class的相关配置 14 | * 15 | * @author jianghang 2011-6-21 下午01:33:28 16 | */ 17 | public class FunctionClassParse { 18 | 19 | private final static Logger logger = LoggerFactory.getLogger(FunctionClassParse.class); 20 | 21 | public static void parseAndRegister(Node node) { 22 | NodeList nodeList = node.getChildNodes(); 23 | for (int i = 0; i < nodeList.getLength(); i++) { 24 | Node aliasClassNode = nodeList.item(i); 25 | if ("functionClass".equals(aliasClassNode.getNodeName())) { 26 | Node nameNode = aliasClassNode.getAttributes().getNamedItem("name"); 27 | Node clazzNode = aliasClassNode.getAttributes().getNamedItem("class"); 28 | if (nameNode == null || clazzNode == null) { 29 | throw new BeanMappingException("alias or class is null , please check!"); 30 | } 31 | 32 | String name = nameNode.getNodeValue(); 33 | Class clazz = ReflectionHelper.forName(clazzNode.getNodeValue()); 34 | ScriptHelper.getInstance().registerFunctionClass(name, ReflectionHelper.newInstance(clazz)); 35 | if (logger.isDebugEnabled()) { 36 | logger.debug("register class[" + clazz.toString() + "] to name[" + name + "]"); 37 | } 38 | } 39 | } 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/helper/BatchObjectHolder.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.helper; 2 | 3 | import com.alibaba.tamper.core.BeanMappingException; 4 | 5 | /** 6 | * 批量处理对象的holder处理 7 | * 8 | * @author jianghang 2011-6-2 下午12:44:26 9 | */ 10 | public class BatchObjectHolder { 11 | 12 | private Object[] batchValues = null; 13 | private int currentIndex; 14 | 15 | public void setBatchValues(Object[] batchValues) { 16 | this.batchValues = batchValues; 17 | } 18 | 19 | public BatchObjectHolder(Object[] values){ 20 | if (values == null) { 21 | throw new BeanMappingException("batch values is null!"); 22 | } 23 | this.batchValues = values; 24 | this.currentIndex = -1; 25 | } 26 | 27 | public Object[] getBatchValues() { 28 | return batchValues; 29 | } 30 | 31 | public Object getNext() { 32 | currentIndex = currentIndex + 1; 33 | if (currentIndex > batchValues.length) { 34 | throw new BeanMappingException("batch values index is out of Array!"); 35 | } 36 | return batchValues[currentIndex]; 37 | } 38 | 39 | public void setObject(Object value) { 40 | batchValues[currentIndex] = value; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/helper/ContextObjectHolder.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.helper; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | /** 7 | * 每个mapping执行过程都认为是在一个独立的Region中进行处理,在Region中会记录一下当前的一些信息 8 | * 9 | * @author jianghang 2012-4-5 下午02:27:41 10 | */ 11 | public class ContextObjectHolder { 12 | 13 | private static volatile ContextObjectHolder singleton = null; 14 | public static final String MAPPING_ENTER = "_mapping_enter_"; 15 | public static final String SCRIPT_CONTEXT = "_script_context_"; 16 | public static final String PROCESS_CONTEXT = "_process_context_"; 17 | private ThreadLocal> context = new ThreadLocal>() { 18 | 19 | protected Map initialValue() { 20 | return new HashMap(10); 21 | } 22 | 23 | }; 24 | 25 | public ContextObjectHolder(){ 26 | 27 | } 28 | 29 | /** 30 | * 单例方法 31 | */ 32 | public static ContextObjectHolder getInstance() { 33 | if (singleton == null) { 34 | synchronized (ContextObjectHolder.class) { 35 | if (singleton == null) { // double check 36 | singleton = new ContextObjectHolder(); 37 | } 38 | } 39 | } 40 | return singleton; 41 | } 42 | 43 | public boolean enter() { 44 | Map map = context.get(); 45 | Object value = map.put(MAPPING_ENTER, true); 46 | return value == null; // 如果value为null,说明是第一次进入 47 | } 48 | 49 | public void clear() { 50 | context.get().clear(); 51 | } 52 | 53 | public void put(Object key, Object value) { 54 | this.context.get().put(key, value); 55 | } 56 | 57 | public Object get(Object key) { 58 | return this.context.get().get(key); 59 | } 60 | 61 | public Object remove(Object key) { 62 | return this.context.get().remove(key); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/helper/XmlHelper.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.helper; 2 | 3 | import java.io.InputStream; 4 | 5 | import javax.xml.XMLConstants; 6 | import javax.xml.parsers.DocumentBuilder; 7 | import javax.xml.parsers.DocumentBuilderFactory; 8 | import javax.xml.transform.stream.StreamSource; 9 | import javax.xml.validation.Schema; 10 | import javax.xml.validation.SchemaFactory; 11 | 12 | import org.w3c.dom.Document; 13 | import org.xml.sax.ErrorHandler; 14 | import org.xml.sax.SAXException; 15 | import org.xml.sax.SAXParseException; 16 | 17 | import com.alibaba.tamper.core.BeanMappingException; 18 | 19 | /** 20 | * xml处理的一些简单包装 21 | * 22 | * @author jianghang 2011-5-26 下午10:07:25 23 | */ 24 | public class XmlHelper { 25 | 26 | public static Document createDocument(InputStream xml, InputStream schema) { 27 | try { 28 | // schema 29 | SchemaFactory sf = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); 30 | Schema s = sf.newSchema(new StreamSource(schema)); 31 | // document 32 | DocumentBuilderFactory bf = DocumentBuilderFactory.newInstance(); 33 | bf.setNamespaceAware(true); 34 | bf.setSchema(s); 35 | DocumentBuilder builder = bf.newDocumentBuilder(); 36 | builder.setErrorHandler(new ErrorHandler() { 37 | 38 | @Override 39 | public void warning(SAXParseException exception) throws SAXException { 40 | throw new BeanMappingException("Xml Parser Warning.", exception); 41 | } 42 | 43 | @Override 44 | public void fatalError(SAXParseException exception) throws SAXException { 45 | throw new BeanMappingException("Xml Parser Fetal Error.", exception); 46 | } 47 | 48 | @Override 49 | public void error(SAXParseException exception) throws SAXException { 50 | throw new BeanMappingException("Xml Parser Error.", exception); 51 | } 52 | }); 53 | return builder.parse(xml); 54 | } catch (Exception e) { 55 | throw new BeanMappingException("Xml Parser Error.", e); 56 | } 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/introspect/AbstractBatchExecutor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.introspect; 2 | 3 | /** 4 | * 批量操作的抽象父类 5 | * 6 | * @author jianghang 2011-6-2 下午04:57:47 7 | */ 8 | public abstract class AbstractBatchExecutor implements BatchExecutor { 9 | 10 | protected final Class objectClass; // 操作object class 11 | 12 | public AbstractBatchExecutor(Class theClass){ 13 | this.objectClass = theClass; 14 | } 15 | 16 | public abstract boolean isAlive(); 17 | 18 | public Class getObjectClass() { 19 | return objectClass; 20 | } 21 | 22 | } 23 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/introspect/AbstractExecutor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.introspect; 2 | 3 | /** 4 | * @author jianghang 2011-5-25 上午11:21:47 5 | */ 6 | public abstract class AbstractExecutor { 7 | 8 | protected final Class objectClass; // 操作object class 9 | protected final String property; // 操作object class 10 | 11 | protected AbstractExecutor(Class theClass, String property){ 12 | this.objectClass = theClass; 13 | this.property = property; 14 | } 15 | 16 | public abstract boolean isAlive(); 17 | 18 | public Class getTargetClass() { 19 | return objectClass; 20 | } 21 | 22 | public String getTargetProperty() { 23 | return property; 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/introspect/BatchExecutor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.introspect; 2 | 3 | import com.alibaba.tamper.core.BeanMappingException; 4 | 5 | /** 6 | * 针对一个obj对象,批量处理的get/set操作 7 | * 8 | * @author jianghang 2011-5-31 下午08:41:14 9 | */ 10 | public interface BatchExecutor { 11 | 12 | Object[] gets(Object obj) throws BeanMappingException; 13 | 14 | void sets(Object obj, Object[] values) throws BeanMappingException; 15 | 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/introspect/FastPropertyGetExecutor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.introspect; 2 | 3 | import net.sf.cglib.reflect.FastMethod; 4 | 5 | import com.alibaba.tamper.core.BeanMappingException; 6 | 7 | /** 8 | * bean 属性的获取 9 | * 10 | * @author jianghang 2011-5-25 下午12:37:50 11 | */ 12 | public class FastPropertyGetExecutor extends AbstractExecutor implements GetExecutor { 13 | 14 | private FastMethod method; 15 | 16 | public FastPropertyGetExecutor(Introspector is, Class clazz, String identifier){ 17 | super(clazz, identifier); 18 | method = discover(is, clazz, identifier); 19 | } 20 | 21 | @Override 22 | public Object invoke(Object obj) throws BeanMappingException { 23 | try { 24 | return (method == null ? null : method.invoke(obj, (Object[]) null)); 25 | } catch (Exception e) { 26 | throw new BeanMappingException(e); 27 | } 28 | } 29 | 30 | @Override 31 | public boolean isAlive() { 32 | return method != null; 33 | } 34 | 35 | public static FastMethod discover(Introspector is, Class clazz, String property) { 36 | FastMethod method = discoverGet(is, "get", clazz, property); 37 | if (method == null) { 38 | // 尝试一下"is"方法 39 | method = discoverGet(is, "is", clazz, property); 40 | } 41 | return method; 42 | } 43 | 44 | public static FastMethod discoverGet(Introspector is, String which, Class clazz, String property) { 45 | FastMethod method = null; 46 | final int start = which.length(); // "get" or "is" 情况处理 47 | StringBuilder sb = new StringBuilder(which); 48 | sb.append(property); 49 | char c = sb.charAt(start); 50 | sb.setCharAt(start, Character.toUpperCase(c));// 转化为 getXxx() 51 | method = is.getFastMethod(clazz, sb.toString()); 52 | // lowercase nth char 53 | if (method == null) { 54 | sb.setCharAt(start, Character.toLowerCase(c)); 55 | method = is.getFastMethod(clazz, sb.toString()); 56 | } 57 | return method; 58 | } 59 | 60 | public FastMethod getMethod() { 61 | return this.method; 62 | } 63 | 64 | } 65 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/introspect/FastPropertySetExecutor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.introspect; 2 | 3 | import java.lang.reflect.Method; 4 | 5 | import net.sf.cglib.reflect.FastClass; 6 | import net.sf.cglib.reflect.FastMethod; 7 | 8 | import com.alibaba.tamper.core.BeanMappingException; 9 | 10 | /** 11 | * pojo bean属性的set操作 12 | * 13 | * @author jianghang 2011-5-25 下午01:04:50 14 | */ 15 | public class FastPropertySetExecutor extends AbstractExecutor implements SetExecutor { 16 | 17 | private FastMethod method; 18 | 19 | public FastPropertySetExecutor(Introspector is, Class clazz, String identifier, Class arg){ 20 | super(clazz, identifier); 21 | method = discover(is, clazz, identifier, arg); 22 | } 23 | 24 | @Override 25 | public Object invoke(Object key, Object value) throws BeanMappingException { 26 | Object[] pargs = { value }; 27 | try { 28 | method.invoke(key, pargs); 29 | return value; 30 | } catch (Exception e) { 31 | throw new BeanMappingException(e); 32 | } 33 | } 34 | 35 | @Override 36 | public boolean isAlive() { 37 | return method != null; 38 | } 39 | 40 | public static FastMethod discover(Introspector is, Class clazz, String property, Class arg) { 41 | String prefix = "set"; 42 | final int start = prefix.length(); // "get" or "is" 情况处理 43 | 44 | StringBuilder sb = new StringBuilder(prefix); 45 | sb.append(property); 46 | char c = sb.charAt(start); 47 | sb.setCharAt(start, Character.toUpperCase(c));// 转化为 setXxx() 48 | if (arg == null) { // 参数为空,根据method name进行查找 49 | Method method = is.getJavaMethod(clazz, sb.toString()); // 注意,不加参数进行查找 50 | // lowercase nth char 51 | if (method == null) { 52 | sb.setCharAt(start, Character.toLowerCase(c)); 53 | method = is.getJavaMethod(clazz, sb.toString()); // 注意,不加参数进行查找 54 | } 55 | 56 | if (method != null) { 57 | FastClass fc = is.getFastClass(clazz); 58 | return fc.getMethod(method); 59 | } else { 60 | return null; 61 | } 62 | } else {// 明确指定参数,根据method name + param进行查找 63 | FastMethod fastMethod = is.getFastMethod(clazz, sb.toString(), arg); 64 | // lowercase nth char 65 | if (fastMethod == null) { 66 | sb.setCharAt(start, Character.toLowerCase(c)); 67 | fastMethod = is.getFastMethod(clazz, sb.toString(), arg); 68 | } 69 | 70 | return fastMethod; 71 | } 72 | 73 | } 74 | 75 | public FastMethod getMethod() { 76 | return this.method; 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/introspect/FieldGetExecutor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.introspect; 2 | 3 | import java.lang.reflect.Field; 4 | 5 | import com.alibaba.tamper.core.BeanMappingException; 6 | 7 | /** 8 | * 基于field属性的直接操作 9 | * 10 | * @author jianghang 2011-6-27 下午08:05:06 11 | */ 12 | public class FieldGetExecutor extends AbstractExecutor implements GetExecutor { 13 | 14 | private Field field; 15 | 16 | protected FieldGetExecutor(Introspector is, Class clazz, String identifier){ 17 | super(clazz, identifier); 18 | field = discover(is, clazz, identifier); 19 | } 20 | 21 | @Override 22 | public boolean isAlive() { 23 | return field != null; 24 | } 25 | 26 | @Override 27 | public Object invoke(Object obj) throws BeanMappingException { 28 | try { 29 | return field.get(obj); 30 | } catch (Exception e) { 31 | throw new BeanMappingException("field invoke error!", e); 32 | } 33 | } 34 | 35 | public static Field discover(Introspector is, Class clazz, String property) { 36 | Field field = is.getField(clazz, property);// 直接通过class获取属性 37 | if (field != null) { 38 | field.setAccessible(true); // 设置为true 39 | return field; 40 | } else { 41 | return null; 42 | } 43 | } 44 | 45 | public Field getField() { 46 | return field; 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/introspect/FieldSetExecutor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.introspect; 2 | 3 | import java.lang.reflect.Field; 4 | 5 | import com.alibaba.tamper.core.BeanMappingException; 6 | 7 | /** 8 | * 基于field属性的直接操作 9 | * 10 | * @author jianghang 2011-6-27 下午08:05:41 11 | */ 12 | public class FieldSetExecutor extends AbstractExecutor implements SetExecutor { 13 | 14 | private Field field; 15 | 16 | protected FieldSetExecutor(Introspector is, Class clazz, String identifier, Class arg){ 17 | super(clazz, identifier); 18 | field = discover(is, clazz, identifier, arg); 19 | } 20 | 21 | @Override 22 | public boolean isAlive() { 23 | return field != null; 24 | } 25 | 26 | @Override 27 | public Object invoke(Object obj, Object value) throws BeanMappingException { 28 | try { 29 | field.set(obj, value); 30 | return value; 31 | } catch (Exception e) { 32 | throw new BeanMappingException("field invoke error!", e); 33 | } 34 | } 35 | 36 | public static Field discover(Introspector is, Class clazz, String property, Class arg) { 37 | Field field = is.getField(clazz, property);// 直接通过class获取属性 38 | if (field != null) { 39 | if (arg != null && field.getType() != arg) { // 判断类型是否匹配 40 | return null; 41 | } 42 | 43 | field.setAccessible(true); // 设置为true 44 | return field; 45 | } else { 46 | return null; 47 | } 48 | } 49 | 50 | public Field getField() { 51 | return field; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/introspect/GetExecutor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.introspect; 2 | 3 | import com.alibaba.tamper.core.BeanMappingException; 4 | 5 | /** 6 | * 属性的Get方法操作接口 7 | * 8 | * @author jianghang 2011-5-25 上午11:14:28 9 | */ 10 | public interface GetExecutor { 11 | 12 | Object invoke(Object obj) throws BeanMappingException; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/introspect/MapBatchExecutor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.introspect; 2 | 3 | import java.util.Map; 4 | 5 | import com.alibaba.tamper.core.BeanMappingException; 6 | 7 | /** 8 | * @author jianghang 2011-6-2 下午04:47:52 9 | */ 10 | public class MapBatchExecutor extends AbstractBatchExecutor { 11 | 12 | private static Object MAP = new Object(); 13 | private Object executor = null; 14 | private Object[] properties; 15 | 16 | public MapBatchExecutor(Introspector is, Class clazz, Object[] fields){ 17 | super(clazz); 18 | this.properties = fields; 19 | executor = discover(clazz); 20 | } 21 | 22 | public Object[] gets(Object obj) throws BeanMappingException { 23 | final Map map = (Map) obj; 24 | Object[] values = new Object[properties.length]; 25 | for (int i = 0; i < properties.length; i++) { 26 | values[i] = map.get(properties[i]); 27 | 28 | } 29 | return values; 30 | } 31 | 32 | public void sets(Object obj, Object[] values) throws BeanMappingException { 33 | final Map map = (Map) obj; 34 | for (int i = 0; i < properties.length; i++) { 35 | map.put(properties[i], values[i]); 36 | 37 | } 38 | } 39 | 40 | @Override 41 | public boolean isAlive() { 42 | return executor != null; 43 | } 44 | 45 | public static Object discover(Class clazz) { 46 | return (Map.class.isAssignableFrom(clazz)) ? MAP : null; 47 | } 48 | 49 | } 50 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/introspect/MapGetExecutor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.introspect; 2 | 3 | import java.util.Map; 4 | 5 | import com.alibaba.tamper.core.BeanMappingException; 6 | 7 | /** 8 | * 基于map的属性get动作处理 9 | * 10 | * @author jianghang 2011-5-25 上午11:32:33 11 | */ 12 | public class MapGetExecutor extends AbstractExecutor implements GetExecutor { 13 | 14 | private boolean flag = false; 15 | 16 | public MapGetExecutor(Introspector is, Class clazz, String key){ 17 | super(clazz, key); 18 | flag = discover(clazz); 19 | } 20 | 21 | @Override 22 | public Object invoke(Object obj) throws BeanMappingException { 23 | final Map map = (Map) obj; 24 | return map.get(property); 25 | } 26 | 27 | @Override 28 | public boolean isAlive() { 29 | return flag; 30 | } 31 | 32 | public static boolean discover(Class clazz) { 33 | return (Map.class.isAssignableFrom(clazz)) ? true : false; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/introspect/MapSetExecutor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.introspect; 2 | 3 | import java.util.Map; 4 | 5 | import com.alibaba.tamper.core.BeanMappingException; 6 | 7 | /** 8 | * 基于map的set操作 9 | * 10 | * @author jianghang 2011-5-25 下午01:02:03 11 | */ 12 | public class MapSetExecutor extends AbstractExecutor implements SetExecutor { 13 | 14 | private boolean flag = false; 15 | 16 | public MapSetExecutor(Introspector is, Class clazz, String key, Class arg){ 17 | super(clazz, key); 18 | flag = discover(clazz); 19 | } 20 | 21 | @Override 22 | public Object invoke(Object obj, Object value) throws BeanMappingException { 23 | final Map map = ((Map) obj); 24 | map.put(property, value); 25 | return value; 26 | } 27 | 28 | @Override 29 | public boolean isAlive() { 30 | return flag; 31 | } 32 | 33 | public static boolean discover(Class clazz) { 34 | return (Map.class.isAssignableFrom(clazz)) ? true : false; 35 | } 36 | 37 | } 38 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/introspect/NullSymbolGetExecutor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.introspect; 2 | 3 | import com.alibaba.tamper.core.BeanMappingException; 4 | 5 | /** 6 | * 处理下特殊符号的get操作,比如针对"null"返回null值 7 | * 8 | * @author jianghang 2012-4-6 下午02:48:25 9 | */ 10 | public class NullSymbolGetExecutor extends AbstractExecutor implements GetExecutor { 11 | 12 | private boolean flag = false; 13 | 14 | public NullSymbolGetExecutor(Introspector is, Class clazz, String key){ 15 | super(clazz, key); 16 | flag = discover(property); 17 | } 18 | 19 | @Override 20 | public Object invoke(Object obj) throws BeanMappingException { 21 | if (flag) { 22 | return null;// 始终返回null值 23 | } 24 | throw new BeanMappingException("error flag"); 25 | } 26 | 27 | public static boolean discover(String key) { 28 | return "null".equalsIgnoreCase(key) ? true : false; 29 | } 30 | 31 | @Override 32 | public boolean isAlive() { 33 | return flag; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/introspect/PropertyBatchExecutor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.introspect; 2 | 3 | import net.sf.cglib.beans.BulkBean; 4 | import net.sf.cglib.reflect.FastMethod; 5 | 6 | import com.alibaba.tamper.core.BeanMappingException; 7 | 8 | /** 9 | * 基于Property属性的batch处理:支持get/set的批量处理 10 | * 11 | * @author jianghang 2011-5-31 下午09:00:24 12 | */ 13 | public class PropertyBatchExecutor extends AbstractBatchExecutor { 14 | 15 | private BulkBean bulkBean = null; 16 | 17 | public PropertyBatchExecutor(Introspector is, Class clazz, String[] fields, Class[] args){ 18 | super(clazz); 19 | bulkBean = buildGetBulkBean(is, clazz, fields, args); 20 | } 21 | 22 | public Object[] gets(Object obj) throws BeanMappingException { 23 | return bulkBean.getPropertyValues(obj); 24 | } 25 | 26 | public void sets(Object obj, Object[] values) throws BeanMappingException { 27 | bulkBean.setPropertyValues(obj, values); 28 | } 29 | 30 | /** 31 | * 判断当前executor是否可用 32 | * 33 | * @return 34 | */ 35 | public final boolean isAlive() { 36 | return (bulkBean != null); 37 | } 38 | 39 | protected BulkBean buildGetBulkBean(Introspector is, Class clazz, String[] fields, Class[] args) { 40 | if (fields.length != args.length) { 41 | throw new BeanMappingException("fields and args size is not match!"); 42 | } 43 | 44 | String[] getters = new String[fields.length]; 45 | String[] setters = new String[fields.length]; 46 | for (int i = 0; i < fields.length; i++) { 47 | String property = fields[i]; 48 | Class arg = args[i]; 49 | FastMethod setMethod = FastPropertySetExecutor.discover(is, clazz, property, arg); 50 | FastMethod getMethod = FastPropertyGetExecutor.discover(is, clazz, property); 51 | if (setMethod == null) { 52 | throw new BeanMappingException("class[" + clazz.getName() + "] field[" + property + "] arg[" 53 | + arg.getName() + "] set Method is not exist!"); 54 | } 55 | 56 | if (getMethod == null) { 57 | throw new BeanMappingException("class[" + clazz.getName() + "] field[" + property 58 | + "] get Method is not exist!"); 59 | } 60 | 61 | if (getMethod.getReturnType() != arg) { 62 | throw new BeanMappingException("class[" + clazz.getName() + "] field[" + property 63 | + "] getMethod does not match declared type"); 64 | } 65 | setters[i] = setMethod.getName(); 66 | getters[i] = getMethod.getName(); 67 | } 68 | 69 | bulkBean = BulkBean.create(clazz, getters, setters, args); 70 | return bulkBean; 71 | } 72 | 73 | } 74 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/introspect/PropertyGetExecutor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.introspect; 2 | 3 | import java.lang.reflect.Method; 4 | 5 | import com.alibaba.tamper.core.BeanMappingException; 6 | 7 | /** 8 | * bean 属性的获取 9 | * 10 | * @author jianghang 2011-5-25 下午12:37:50 11 | */ 12 | public class PropertyGetExecutor extends AbstractExecutor implements GetExecutor { 13 | 14 | private Method method; 15 | 16 | public PropertyGetExecutor(Introspector is, Class clazz, String identifier){ 17 | super(clazz, identifier); 18 | method = discover(is, clazz, identifier); 19 | } 20 | 21 | @Override 22 | public Object invoke(Object obj) throws BeanMappingException { 23 | try { 24 | return (method == null ? null : method.invoke(obj, (Object[]) null)); 25 | } catch (Exception e) { 26 | throw new BeanMappingException(e); 27 | } 28 | } 29 | 30 | @Override 31 | public boolean isAlive() { 32 | return method != null; 33 | } 34 | 35 | public static Method discover(Introspector is, Class clazz, String property) { 36 | Method method = discoverGet(is, "get", clazz, property); 37 | if (method == null) { 38 | // 尝试一下"is"方法 39 | method = discoverGet(is, "is", clazz, property); 40 | if (method == null) { 41 | // 特殊处理 boolean isSuccessed生成的set/get方法为isSucessed(),setSuccessed(),需要过滤属性is前缀 42 | if (property.startsWith("is")) { 43 | property = property.substring("is".length());// 截取掉is前缀 44 | method = discoverGet(is, "is", clazz, property); 45 | } 46 | } 47 | } 48 | 49 | return method; 50 | } 51 | 52 | public static Method discoverGet(Introspector is, String which, Class clazz, String property) { 53 | Method method = null; 54 | final int start = which.length(); // "get" or "is" 情况处理 55 | StringBuilder sb = new StringBuilder(which); 56 | sb.append(property); 57 | char c = sb.charAt(start); 58 | sb.setCharAt(start, Character.toUpperCase(c));// 转化为 getXxx() 59 | method = is.getJavaMethod(clazz, sb.toString()); 60 | // lowercase nth char 61 | if (method == null) { 62 | sb.setCharAt(start, Character.toLowerCase(c)); 63 | method = is.getJavaMethod(clazz, sb.toString()); 64 | } 65 | return method; 66 | } 67 | 68 | public Method getMethod() { 69 | return this.method; 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/introspect/PropertySetExecutor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.introspect; 2 | 3 | import java.lang.reflect.Method; 4 | 5 | import com.alibaba.tamper.core.BeanMappingException; 6 | 7 | /** 8 | * pojo bean属性的set操作 9 | * 10 | * @author jianghang 2011-5-25 下午01:04:50 11 | */ 12 | public class PropertySetExecutor extends AbstractExecutor implements SetExecutor { 13 | 14 | private Method method; 15 | 16 | public PropertySetExecutor(Introspector is, Class clazz, String identifier, Class arg){ 17 | super(clazz, identifier); 18 | method = discover(is, clazz, identifier, arg); 19 | } 20 | 21 | @Override 22 | public Object invoke(Object key, Object value) throws BeanMappingException { 23 | Object[] pargs = { value }; 24 | try { 25 | method.invoke(key, pargs); 26 | return value; 27 | } catch (Exception e) { 28 | throw new BeanMappingException(e); 29 | } 30 | } 31 | 32 | @Override 33 | public boolean isAlive() { 34 | return method != null; 35 | } 36 | 37 | public static Method discover(Introspector is, Class clazz, String property, Class arg) { 38 | Method method = discoverSet(is, clazz, property, arg); 39 | if (method == null) { 40 | // 特殊处理 boolean isSuccessed生成的set/get方法为isSucessed(),setSuccessed(),需要过滤属性is前缀 41 | if (property.startsWith("is")) { 42 | property = property.substring("is".length());// 截取掉is前缀 43 | method = discoverSet(is, clazz, property, arg); 44 | } 45 | } 46 | return method; 47 | } 48 | 49 | public static Method discoverSet(Introspector is, Class clazz, String property, Class arg) { 50 | String prefix = "set"; 51 | final int start = prefix.length(); // "get" or "is" 情况处理 52 | 53 | StringBuilder sb = new StringBuilder(prefix); 54 | sb.append(property); 55 | char c = sb.charAt(start); 56 | sb.setCharAt(start, Character.toUpperCase(c));// 转化为 setXxx() 57 | if (arg == null) { // 参数为空,根据method name进行查找 58 | Method method = is.getJavaMethod(clazz, sb.toString()); // 注意,不加参数进行查找 59 | // lowercase nth char 60 | if (method == null) { 61 | sb.setCharAt(start, Character.toLowerCase(c)); 62 | method = is.getJavaMethod(clazz, sb.toString()); // 注意,不加参数进行查找 63 | } 64 | 65 | return method; 66 | } else {// 明确指定参数,根据method name + param进行查找 67 | Method method = is.getJavaMethod(clazz, sb.toString(), arg); 68 | // lowercase nth char 69 | if (method == null) { 70 | sb.setCharAt(start, Character.toLowerCase(c)); 71 | method = is.getJavaMethod(clazz, sb.toString(), arg); 72 | } 73 | 74 | return method; 75 | } 76 | } 77 | 78 | public Method getMethod() { 79 | return this.method; 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/introspect/SetExecutor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.introspect; 2 | 3 | import com.alibaba.tamper.core.BeanMappingException; 4 | 5 | /** 6 | * 属性的Set方法操作接口 7 | * 8 | * @author jianghang 2011-5-25 上午11:14:07 9 | */ 10 | public interface SetExecutor { 11 | 12 | Object invoke(Object key, Object value) throws BeanMappingException; 13 | } 14 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/introspect/ThisSymbolGetExecutor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.introspect; 2 | 3 | import com.alibaba.tamper.core.BeanMappingException; 4 | 5 | /** 6 | * 处理下特殊符号的get操作,比如针对"this"返回当前对象的引用 7 | * 8 | * @author jianghang 2011-6-27 下午07:58:25 9 | */ 10 | public class ThisSymbolGetExecutor extends AbstractExecutor implements GetExecutor { 11 | 12 | private boolean flag = false; 13 | 14 | public ThisSymbolGetExecutor(Introspector is, Class clazz, String key){ 15 | super(clazz, key); 16 | flag = discover(property); 17 | } 18 | 19 | @Override 20 | public Object invoke(Object obj) throws BeanMappingException { 21 | if (flag) { 22 | return obj; 23 | } 24 | throw new BeanMappingException("error flag"); 25 | } 26 | 27 | public static boolean discover(String key) { 28 | return "this".equalsIgnoreCase(key) ? true : false; 29 | } 30 | 31 | @Override 32 | public boolean isAlive() { 33 | return flag; 34 | } 35 | 36 | } 37 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/introspect/Uberspect.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.introspect; 2 | 3 | /** 4 | * 暴露给外部的内审接口操作 5 | * 6 | * @author jianghang 2011-5-25 下午01:18:18 7 | */ 8 | public interface Uberspect { 9 | 10 | /** 11 | * 根据对应的信息返回executor 12 | */ 13 | public BatchExecutor getBatchExecutor(Class locatorClass, String[] identifier, Class[] args); 14 | 15 | /** 16 | * 根据对应的信息返回executor 17 | */ 18 | public GetExecutor getGetExecutor(Class locatorClass, Object identifier); 19 | 20 | /** 21 | * 根据对应的信息返回executor 22 | */ 23 | public SetExecutor getSetExecutor(Class locatorClass, Object identifier, Class arg); 24 | 25 | /** 26 | * 根据executor返回对应的参数类型 27 | */ 28 | public Class getGetClass(GetExecutor getExecutor, Class srcRefClass, Class getResultClass); 29 | 30 | /** 31 | * 根据executor返回对应的参数类型 32 | */ 33 | public Class getSetClass(SetExecutor setExecutor, Class srcRefClass, Class getResultClass); 34 | } 35 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/introspect/Uberspector.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.introspect; 2 | 3 | import com.alibaba.tamper.core.config.BeanMappingEnvironment; 4 | 5 | /** 6 | * 暴露给外部的内审接口操作,外部可通过Uberspector.getInstance()进行操作 7 | * 8 | * @author jianghang 2011-5-25 下午01:18:18 9 | */ 10 | public class Uberspector { 11 | 12 | private static volatile Uberspect singleton; 13 | 14 | public static Uberspect getInstance() { 15 | if (singleton == null) { 16 | synchronized (Uberspector.class) { 17 | if (singleton == null) { // double check 18 | singleton = BeanMappingEnvironment.getUberspect(); 19 | } 20 | } 21 | } 22 | return singleton; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/process/ValueProcess.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.process; 2 | 3 | import com.alibaba.tamper.core.BeanMappingException; 4 | 5 | /** 6 | * 数据处理接口,允许在get Executor执行之前处理下value。 7 | * 8 | * @author jianghang 2011-5-25 下午01:39:25 9 | */ 10 | public interface ValueProcess { 11 | 12 | public Object process(Object value, ValueProcessInvocation invocation) throws BeanMappingException; 13 | 14 | } 15 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/process/ValueProcessContext.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.process; 2 | 3 | import java.io.Serializable; 4 | import java.util.Map; 5 | 6 | import com.alibaba.tamper.core.BeanMappingParam; 7 | import com.alibaba.tamper.core.config.BeanMappingField; 8 | import com.alibaba.tamper.core.config.BeanMappingObject; 9 | import com.alibaba.tamper.core.helper.BatchObjectHolder; 10 | 11 | /** 12 | * ValueProcess处理的上下文,允许ValueProcess基于context进行自定义的处理 13 | * 14 | * @author jianghang 2011-5-27 下午09:01:39 15 | */ 16 | public class ValueProcessContext implements Serializable { 17 | 18 | private static final long serialVersionUID = 5690443269510349965L; 19 | private BeanMappingParam param; 20 | private BeanMappingObject beanObject; 21 | private BeanMappingField currentField; 22 | private BatchObjectHolder holder; 23 | private Map custom; // 允许自定义的context 24 | 25 | public ValueProcessContext(BeanMappingParam param, BeanMappingObject object, BeanMappingField field, 26 | BatchObjectHolder holder){ 27 | this(param, object, field, holder, null); 28 | } 29 | 30 | public ValueProcessContext(BeanMappingParam param, BeanMappingObject object, BeanMappingField field, 31 | BatchObjectHolder holder, Map customContext){ 32 | this.param = param; 33 | this.beanObject = object; 34 | this.currentField = field; 35 | this.holder = holder; 36 | this.custom = customContext; 37 | } 38 | 39 | public BeanMappingParam getParam() { 40 | return param; 41 | } 42 | 43 | public void setParam(BeanMappingParam param) { 44 | this.param = param; 45 | } 46 | 47 | public BeanMappingObject getBeanObject() { 48 | return beanObject; 49 | } 50 | 51 | public void setBeanObject(BeanMappingObject beanObject) { 52 | this.beanObject = beanObject; 53 | } 54 | 55 | public BeanMappingField getCurrentField() { 56 | return currentField; 57 | } 58 | 59 | public void setCurrentField(BeanMappingField currentField) { 60 | this.currentField = currentField; 61 | } 62 | 63 | public BatchObjectHolder getHolder() { 64 | return holder; 65 | } 66 | 67 | public void setHolder(BatchObjectHolder holder) { 68 | this.holder = holder; 69 | } 70 | 71 | public Map getCustom() { 72 | return custom; 73 | } 74 | 75 | public void setCustom(Map custom) { 76 | this.custom = custom; 77 | } 78 | 79 | } 80 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/core/process/ValueProcessInvocation.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.core.process; 2 | 3 | import java.util.List; 4 | 5 | import com.alibaba.tamper.core.BeanMappingException; 6 | import com.alibaba.tamper.core.introspect.GetExecutor; 7 | import com.alibaba.tamper.core.introspect.SetExecutor; 8 | 9 | /** 10 | * ValueProcess执行的get操作的控制器 11 | * 12 | * @author jianghang 2011-5-30 上午07:44:02 13 | */ 14 | public class ValueProcessInvocation { 15 | 16 | private ValueProcessContext context; // valueProcess执行的上下文参数 17 | private List processes; // 处理的process列表 18 | private GetExecutor getExecutor; // get方法调用 19 | private SetExecutor setExecutor; // set方法调用 20 | private int currentIndex = -1; // 当前执行的valueProcess下标 21 | 22 | public ValueProcessInvocation(GetExecutor getExecutor, SetExecutor setExecutor, ValueProcessContext context, 23 | List processes){ 24 | this.getExecutor = getExecutor; 25 | this.setExecutor = setExecutor; 26 | this.context = context; 27 | this.processes = processes; 28 | } 29 | 30 | /** 31 | * 获取初始value值 32 | */ 33 | public Object getInitialValue() { 34 | return invokeGetExecutor(); 35 | } 36 | 37 | public Object proceed(Object value) throws BeanMappingException { 38 | if (processes == null) { // 如果处理列表为空,则直接调用 39 | return invokeSetExecutor(value); 40 | } else { 41 | if (this.currentIndex == this.processes.size() - 1) { 42 | return invokeSetExecutor(value); 43 | } else { 44 | ValueProcess vp = this.processes.get(++this.currentIndex); 45 | return vp.process(value, this); 46 | } 47 | } 48 | 49 | } 50 | 51 | /** 52 | * 执行GetExecutor 53 | */ 54 | protected Object invokeGetExecutor() { 55 | if (isGetBatch()) { // 如果是batch模式 56 | return context.getHolder().getNext(); 57 | } 58 | 59 | if (getExecutor != null) { 60 | return getExecutor.invoke(context.getParam().getSrcRef()); 61 | } else { 62 | return null; 63 | } 64 | } 65 | 66 | /** 67 | * 执行SetExecutor 68 | */ 69 | protected Object invokeSetExecutor(Object value) { 70 | if (isSetBatch()) { // 如果是batch模式 71 | context.getHolder().setObject(value); // 更新下holder的value值 72 | return value; 73 | } 74 | 75 | if (setExecutor != null) { 76 | return setExecutor.invoke(context.getParam().getTargetRef(), value); 77 | } else { 78 | return null; 79 | } 80 | } 81 | 82 | /** 83 | * 判断当前是否处于debug模式 84 | */ 85 | public boolean isDebug() { 86 | return getContext().getBeanObject().getBehavior().isDebug(); 87 | } 88 | 89 | /** 90 | * 判断一下是否处于get batch处理模式 91 | */ 92 | private boolean isGetBatch() { 93 | return context.getBeanObject().isBatch() && context.getBeanObject().getGetBatchExecutor() != null; 94 | } 95 | 96 | /** 97 | * 判断一下是否处于set batch处理模式 98 | */ 99 | private boolean isSetBatch() { 100 | return context.getBeanObject().isBatch() && context.getBeanObject().getSetBatchExecutor() != null; 101 | } 102 | 103 | // =================== get 操作=============== 104 | 105 | public ValueProcessContext getContext() { 106 | return context; 107 | } 108 | 109 | } 110 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/process/BeanCreatorValueProcess.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.process; 2 | 3 | import com.alibaba.tamper.core.BeanMappingException; 4 | import com.alibaba.tamper.core.config.BeanMappingField; 5 | import com.alibaba.tamper.core.helper.ReflectionHelper; 6 | import com.alibaba.tamper.core.process.ValueProcess; 7 | import com.alibaba.tamper.core.process.ValueProcessInvocation; 8 | 9 | /** 10 | * set操作流程中, 尝试创建一下嵌套的bean实例,通过反射newInstance, 11 | * 12 | * @author jianghang 2011-5-28 下午11:32:38 13 | */ 14 | public class BeanCreatorValueProcess implements ValueProcess { 15 | 16 | @Override 17 | public Object process(Object value, ValueProcessInvocation invocation) throws BeanMappingException { 18 | if (value != null) { 19 | BeanMappingField currentField = invocation.getContext().getCurrentField(); 20 | if (currentField.isMapping()) { 21 | // 判断下是否在处理嵌套的mapping 22 | // 这里的value代表从get取出来的嵌套对象,如果有值,说明在目标对象上也需要创建targetClass对象进行复制 23 | value = ReflectionHelper.newInstance(invocation.getContext().getCurrentField().getTargetField().getClazz()); 24 | } 25 | } 26 | 27 | // 继续下一步的调用 28 | return invocation.proceed(value); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/process/BehaviorValueProcess.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 1999-2004 Alibaba.com All right reserved. This software is the confidential and proprietary information of 3 | * Alibaba.com ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only 4 | * in accordance with the terms of the license agreement you entered into with Alibaba.com. 5 | */ 6 | package com.alibaba.tamper.process; 7 | 8 | import org.apache.commons.lang.StringUtils; 9 | 10 | import com.alibaba.tamper.core.BeanMappingException; 11 | import com.alibaba.tamper.core.config.BeanMappingBehavior; 12 | import com.alibaba.tamper.core.config.BeanMappingField; 13 | import com.alibaba.tamper.core.process.ValueProcess; 14 | import com.alibaba.tamper.core.process.ValueProcessInvocation; 15 | 16 | /** 17 | * 处理下Behavior的行为控制, 可参见 {@linkplain BeanMappingBehavior} 18 | * 19 | * @author jianghang 2011-6-22 上午09:50:16 20 | */ 21 | public class BehaviorValueProcess implements ValueProcess { 22 | 23 | public Object process(Object value, ValueProcessInvocation invocation) throws BeanMappingException { 24 | BeanMappingField field = invocation.getContext().getCurrentField(); 25 | BeanMappingBehavior behavior = field.getBehavior(); // 每个属性mapping都会有一个behavior,允许覆盖上层 26 | 27 | // 判断一下value的null 情况 28 | if (value == null && behavior.isMappingNullValue() == false) { 29 | return value; 30 | } 31 | 32 | // 进行trim处理 33 | if (value instanceof String && behavior.isTrimStrings()) { 34 | value = StringUtils.trim((String) value); 35 | } 36 | 37 | // 判断一下String的null / empty情况 38 | if ((value == null || (value instanceof String && StringUtils.isEmpty((String) value))) 39 | && behavior.isMappingEmptyStrings() == false) { 40 | return value; 41 | } 42 | 43 | return invocation.proceed(value); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/process/ConvertorValueProcess.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.process; 2 | 3 | import java.util.List; 4 | 5 | import org.apache.commons.lang.ObjectUtils; 6 | import org.apache.commons.lang.StringUtils; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | 10 | import com.alibaba.tamper.core.BeanMappingException; 11 | import com.alibaba.tamper.core.config.BeanMappingField; 12 | import com.alibaba.tamper.core.helper.ReflectionHelper; 13 | import com.alibaba.tamper.core.process.ValueProcess; 14 | import com.alibaba.tamper.core.process.ValueProcessInvocation; 15 | import com.alibaba.tamper.process.convertor.CollectionConvertor; 16 | import com.alibaba.tamper.process.convertor.Convertor; 17 | import com.alibaba.tamper.process.convertor.ConvertorHelper; 18 | 19 | /** 20 | * {@linkplain Convertor}转化的处理器,set流程处理 21 | * 22 | * @author jianghang 2011-5-27 下午09:30:40 23 | */ 24 | public class ConvertorValueProcess implements ValueProcess { 25 | 26 | private final static Logger logger = LoggerFactory.getLogger(ConvertorValueProcess.class); 27 | 28 | @Override 29 | public Object process(Object value, ValueProcessInvocation invocation) throws BeanMappingException { 30 | if (value != null && invocation.getContext().getCurrentField().isMapping() == false) { 31 | BeanMappingField currentField = invocation.getContext().getCurrentField(); 32 | String customConvertorName = currentField.getConvertor(); 33 | Convertor convertor = currentField.getConvertorRef();// 取上一次实例化后的convertor对象 34 | 35 | if (convertor == null && currentField.getConvertorClass() != null) { 36 | // 进行自定义convertor初始化 37 | Class clazz = currentField.getConvertorClass(); 38 | convertor = (Convertor) ReflectionHelper.newInstance(clazz); 39 | currentField.setConvertorRef(convertor); 40 | } 41 | 42 | if (StringUtils.isNotEmpty(customConvertorName)) { // 判断是否有自定义的convertor 43 | convertor = ConvertorHelper.getInstance().getConvertor(customConvertorName); 44 | } else if (convertor == null) { 45 | // srcClass针对直接使用script的情况,会出现为空,这时候需要依赖value.getClass进行转化 46 | // 优先不选择使用value.getClass()的原因:原生类型会返回对应的Object类型,导出会出现不必要的convertor转化 47 | Class srcClass = currentField.getSrcField().getClazz(); 48 | if (srcClass == null || srcClass.isPrimitive() == false) { 49 | srcClass = value.getClass(); 50 | } 51 | Class targetClass = currentField.getTargetField().getClazz(); 52 | if (targetClass != null) { 53 | // targetClass可能存在为空,比如这里的Value配置了DefaultValue,在MapSetExecutor解析时会无法识别TargetClass 54 | // 无法识别后,就不做转化 55 | convertor = ConvertorHelper.getInstance().getConvertor(srcClass, targetClass); 56 | 57 | if (convertor == null && !targetClass.isAssignableFrom(srcClass) && logger.isWarnEnabled()) { 58 | // 记录下日志 59 | StringBuilder builder = new StringBuilder(); 60 | builder.append("srcName[" + currentField.getSrcField().getName()); 61 | builder.append("],srcClass[" + ObjectUtils.toString(srcClass, "null")); 62 | builder.append("],targetName[" + currentField.getTargetField().getName()); 63 | builder.append("],targetClass[" + ObjectUtils.toString(targetClass, "null") + "]"); 64 | logger.warn(builder.toString() + " convertor is null!"); 65 | } 66 | } 67 | } 68 | 69 | if (convertor != null && currentField.getTargetField().getClazz() != null) { 70 | List componentClasses = currentField.getTargetField().getComponentClasses(); 71 | Class[] array = null; 72 | if (componentClasses != null && componentClasses.size() > 0) { 73 | array = componentClasses.toArray(new Class[componentClasses.size()]); 74 | } 75 | if (array != null && convertor instanceof CollectionConvertor) { 76 | // 进行嵌套对象处理 77 | value = ((CollectionConvertor) convertor).convertCollection( 78 | currentField, 79 | value, 80 | currentField.getTargetField().getClazz(), 81 | array); 82 | } else { 83 | value = convertor.convert(value, currentField.getTargetField().getClazz()); 84 | } 85 | } 86 | } 87 | 88 | // 继续下一步的调用 89 | return invocation.proceed(value); 90 | } 91 | } 92 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/process/DebugValueProcess.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 1999-2004 Alibaba.com All right reserved. This software is the confidential and proprietary information of 3 | * Alibaba.com ("Confidential Information"). You shall not disclose such Confidential Information and shall use it only 4 | * in accordance with the terms of the license agreement you entered into with Alibaba.com. 5 | */ 6 | package com.alibaba.tamper.process; 7 | 8 | import org.apache.commons.lang.ObjectUtils; 9 | import org.apache.commons.lang.StringUtils; 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | 13 | import com.alibaba.tamper.core.BeanMappingException; 14 | import com.alibaba.tamper.core.config.BeanMappingField; 15 | import com.alibaba.tamper.core.process.ValueProcess; 16 | import com.alibaba.tamper.core.process.ValueProcessInvocation; 17 | 18 | /** 19 | * 输出一些日志信息,方便排查问题 20 | * 21 | * @author jianghang 2011-6-10 下午02:24:00 22 | */ 23 | public class DebugValueProcess implements ValueProcess { 24 | 25 | private final static Logger logger = LoggerFactory.getLogger(DebugValueProcess.class); 26 | 27 | @Override 28 | public Object process(Object value, ValueProcessInvocation invocation) throws BeanMappingException { 29 | BeanMappingField currentField = invocation.getContext().getCurrentField(); 30 | if (currentField.isMapping() == false && invocation.getContext().getBeanObject().getBehavior().isDebug() 31 | && logger.isDebugEnabled()) { 32 | StringBuilder builder = new StringBuilder(); 33 | builder.append("srcName[" + currentField.getSrcField().getName()); 34 | builder.append("],srcClass[" + ObjectUtils.toString(currentField.getSrcField().getClazz(), "null")); 35 | builder.append("],targetName[" + currentField.getTargetField().getName()); 36 | builder.append("],targetClass[" + ObjectUtils.toString(currentField.getTargetField().getClazz(), "null")); 37 | if (StringUtils.isNotEmpty(currentField.getDefaultValue())) { 38 | builder.append("],[defaultValue=" + currentField.getDefaultValue()); 39 | } 40 | if (StringUtils.isNotEmpty(currentField.getConvertor())) { 41 | builder.append("],[convertor=" + currentField.getConvertor()); 42 | } 43 | if (StringUtils.isNotEmpty(currentField.getScript())) { 44 | builder.append("],[script=" + currentField.getScript()); 45 | } 46 | builder.append("], Value = " + ObjectUtils.toString(value, "null")); 47 | logger.debug(builder.toString()); 48 | } 49 | return invocation.proceed(value); // 继续传递 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/process/DefaultValueValueProcess.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.process; 2 | 3 | import org.apache.commons.lang.StringUtils; 4 | 5 | import com.alibaba.tamper.core.BeanMappingException; 6 | import com.alibaba.tamper.core.config.BeanMappingField; 7 | import com.alibaba.tamper.core.process.ValueProcess; 8 | import com.alibaba.tamper.core.process.ValueProcessInvocation; 9 | import com.alibaba.tamper.process.convertor.Convertor; 10 | import com.alibaba.tamper.process.convertor.ConvertorHelper; 11 | 12 | /** 13 | * mapping默认值的处理,get流程处理 14 | * 15 | * @author jianghang 2011-5-27 下午09:19:46 16 | */ 17 | public class DefaultValueValueProcess implements ValueProcess { 18 | 19 | @Override 20 | public Object process(Object value, ValueProcessInvocation invocation) throws BeanMappingException { 21 | // 处理下自己的业务 22 | BeanMappingField currentField = invocation.getContext().getCurrentField(); 23 | if (value == null && StringUtils.isNotEmpty(currentField.getDefaultValue()) 24 | && currentField.isMapping() == false) { 25 | if (currentField.getSrcField().getClazz() != null) {// 有指定对应的SrcClass 26 | Convertor convertor = ConvertorHelper.getInstance().getConvertor(String.class, 27 | currentField.getSrcField().getClazz()); 28 | if (convertor != null) { 29 | // 先对String字符串进行一次转化 30 | value = convertor.convert(currentField.getDefaultValue(), currentField.getSrcField().getClazz()); 31 | } 32 | } 33 | 34 | if (value == null) { 35 | // 不存在对默认值处理的convertor,不予处理,后续尝试下自定义的convertor 36 | value = currentField.getDefaultValue(); 37 | } 38 | } 39 | 40 | return invocation.proceed(value); 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/process/ScriptValueProcess.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.process; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import org.apache.commons.lang.StringUtils; 7 | 8 | import com.alibaba.tamper.core.BeanMappingException; 9 | import com.alibaba.tamper.core.config.BeanMappingField; 10 | import com.alibaba.tamper.core.config.BeanMappingObject; 11 | import com.alibaba.tamper.core.helper.ContextObjectHolder; 12 | import com.alibaba.tamper.core.process.ValueProcess; 13 | import com.alibaba.tamper.core.process.ValueProcessInvocation; 14 | import com.alibaba.tamper.process.script.ScriptExecutor; 15 | import com.alibaba.tamper.process.script.ScriptHelper; 16 | 17 | /** 18 | * 自定义script脚本的处理器 , get流程处理 19 | * 20 | * @author jianghang 2011-5-27 下午09:25:17 21 | */ 22 | public class ScriptValueProcess implements ValueProcess { 23 | 24 | @Override 25 | public Object process(Object value, ValueProcessInvocation invocation) throws BeanMappingException { 26 | BeanMappingField currentField = invocation.getContext().getCurrentField(); 27 | if (StringUtils.isNotEmpty(currentField.getScript())) { 28 | BeanMappingObject beanObject = invocation.getContext().getBeanObject(); 29 | 30 | Map param = (Map) ContextObjectHolder.getInstance().get(ContextObjectHolder.SCRIPT_CONTEXT);// 使用第一次记录的script_context 31 | if (param == null) { 32 | param = new HashMap(); 33 | param.put(beanObject.getSrcKey(), invocation.getContext().getParam().getSrcRef()); 34 | param.put(beanObject.getTargetKey(), invocation.getContext().getParam().getTargetRef()); 35 | ContextObjectHolder.getInstance().put(ContextObjectHolder.SCRIPT_CONTEXT, param); 36 | } 37 | 38 | Map custom = invocation.getContext().getCustom(); 39 | if (custom != null && custom.containsKey(ContextObjectHolder.SCRIPT_CONTEXT)) { 40 | Map newParam = (Map) custom.get(ContextObjectHolder.SCRIPT_CONTEXT); 41 | param.putAll(newParam); 42 | } 43 | 44 | // 进行值转化处理 45 | ScriptExecutor scriptExecutor = ScriptHelper.getInstance().getScriptExecutor(); 46 | value = scriptExecutor.evaluate(param, currentField.getScript()); 47 | } 48 | 49 | // 继续走到下一步处理 50 | return invocation.proceed(value); 51 | 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/process/convertor/AbastactConvertor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.process.convertor; 2 | 3 | import com.alibaba.tamper.core.BeanMappingException; 4 | import com.alibaba.tamper.core.config.BeanMappingField; 5 | 6 | /** 7 | * @author jianghang 2011-6-21 下午03:46:57 8 | */ 9 | public class AbastactConvertor implements Convertor, CollectionConvertor { 10 | 11 | @Override 12 | public Object convert(Object src, Class destClass) { 13 | throw new BeanMappingException("unSupport!"); 14 | } 15 | 16 | @Override 17 | public Object convertCollection(Object src, Class destClass, Class... componentClasses) { 18 | throw new BeanMappingException("unSupport!"); 19 | } 20 | 21 | @Override 22 | public Object convertCollection(BeanMappingField context, Object src, Class destClass, Class... componentClasses) { 23 | throw new BeanMappingException("unSupport!"); 24 | } 25 | 26 | } 27 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/process/convertor/CollectionConvertor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.process.convertor; 2 | 3 | import com.alibaba.tamper.core.config.BeanMappingField; 4 | 5 | /** 6 | * 自定义的collection convertor接口, 外部可不关注该接口 7 | * 8 | * @author jianghang 2012-4-5 下午05:18:31 9 | */ 10 | public interface CollectionConvertor extends Convertor { 11 | 12 | /** 13 | * 支持多级collection映射,需指定多级的componentClass 14 | */ 15 | public Object convertCollection(BeanMappingField context, Object src, Class destClass, Class... componentClasses); 16 | } 17 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/process/convertor/Convertor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.process.convertor; 2 | 3 | /** 4 | * 自定义的convertor接口 5 | * 6 | *
 7 |  * 不选择现有convertor的理由:
 8 |  * BeanUtils 不支持alias别名,必须绑定到具体的对象
 9 |  * alibaba convert 支持alias别名,但注册时只是建立class对象和alias之间有一映射关系
10 |  *     
11 |  * 我们的需求:
12 |  * 定义convert,指定对应名字name, 在dsl描述时引用name进行convertor处理
13 |  * 
14 | * 15 | * @author jianghang 2011-5-25 下午10:08:48 16 | */ 17 | public interface Convertor { 18 | 19 | public Object convert(Object src, Class destClass); 20 | 21 | /** 22 | * 支持多级collection映射,需指定多级的componentClass 23 | */ 24 | public Object convertCollection(Object src, Class destClass, Class... componentClasses); 25 | } 26 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/process/convertor/ConvertorRepository.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.process.convertor; 2 | 3 | import java.util.Map; 4 | import java.util.concurrent.ConcurrentHashMap; 5 | 6 | /** 7 | * 定义自己的convertor仓库 8 | * 9 | * @author jianghang 2011-5-25 下午10:16:10 10 | */ 11 | public class ConvertorRepository { 12 | 13 | private static final String SEPERATOR = ":"; 14 | private static String int_name = Integer.class.getName(); 15 | private static String short_name = Short.class.getName(); 16 | private static String long_name = Long.class.getName(); 17 | private static String char_name = Character.class.getName(); 18 | private static String void_name = Void.class.getName(); 19 | private static String double_name = Double.class.getName(); 20 | private static String float_name = Float.class.getName(); 21 | private static String byte_name = Byte.class.getName(); 22 | private static String bool_name = Boolean.class.getName(); 23 | 24 | private Map convertors = new ConcurrentHashMap(10); 25 | 26 | public Convertor getConvertor(Class src, Class dest) { 27 | // 按照src->dest来取映射 28 | return convertors.get(mapperConvertorName(src, dest)); 29 | } 30 | 31 | public Convertor getConvertor(String alias) { 32 | return convertors.get(alias); 33 | } 34 | 35 | public void registerConvertor(Class src, Class dest, Convertor convertor) { 36 | String key = mapperConvertorName(src, dest); 37 | // 对于已经注册的convert,进行覆盖处理 38 | if (convertor != null) { 39 | convertors.put(key, convertor); 40 | } 41 | } 42 | 43 | public void registerConvertor(String alias, Convertor convertor) { 44 | // 对于已经注册的convert,进行覆盖处理 45 | if (convertor != null) { 46 | convertors.put(alias, convertor); 47 | } 48 | } 49 | 50 | // ========================= helper method =================== 51 | 52 | private String mapperConvertorName(Class src, Class dest) { 53 | String name1 = getName(src); 54 | String name2 = getName(dest); 55 | 56 | return name1 + SEPERATOR + name2; 57 | } 58 | 59 | private String getName(Class type) { 60 | if (type.isPrimitive()) { 61 | if (type == int.class) { 62 | return int_name; 63 | } else if (type == short.class) { 64 | return short_name; 65 | } else if (type == long.class) { 66 | return long_name; 67 | } else if (type == char.class) { 68 | return char_name; 69 | } else if (type == void.class) { 70 | return void_name; 71 | } else if (type == double.class) { 72 | return double_name; 73 | } else if (type == float.class) { 74 | return float_name; 75 | } else if (type == byte.class) { 76 | return byte_name; 77 | } else if (type == boolean.class) { 78 | return bool_name; 79 | } 80 | } 81 | 82 | return type.getName(); 83 | } 84 | 85 | } 86 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/process/convertor/SqlDateAndDateConvertor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.process.convertor; 2 | 3 | import java.util.Date; 4 | 5 | import com.alibaba.tamper.core.BeanMappingException; 6 | 7 | /** 8 | * Date <-> SqlDate 之间的转化 9 | * 10 | * @author jianghang 2011-11-16 上午09:47:01 11 | */ 12 | public class SqlDateAndDateConvertor { 13 | 14 | public static class SqlDateToDateConvertor extends AbastactConvertor { 15 | 16 | @Override 17 | public Object convert(Object src, Class destClass) { 18 | if (Date.class != destClass) { 19 | throw new BeanMappingException("Unsupported convert: [" + src + "," + destClass.getName() + "]"); 20 | } 21 | if (src instanceof java.sql.Date) { 22 | return new Date(((java.sql.Date) src).getTime()); 23 | } 24 | if (src instanceof java.sql.Timestamp) { 25 | return new Date(((java.sql.Timestamp) src).getTime()); 26 | } 27 | if (src instanceof java.sql.Time) { 28 | return new Date(((java.sql.Time) src).getTime()); 29 | } 30 | throw new BeanMappingException("Unsupported convert: [" + src + "," + destClass.getName() + "]"); 31 | } 32 | } 33 | 34 | public static class DateToSqlDateConvertor extends AbastactConvertor { 35 | 36 | @Override 37 | public Object convert(Object src, Class destClass) { 38 | if (Date.class.isInstance(src)) { // 必须是字符串 39 | Date date = (Date) src; 40 | long value = date.getTime(); 41 | // java.sql.Date 42 | if (destClass.equals(java.sql.Date.class)) { 43 | return new java.sql.Date(value); 44 | } 45 | 46 | // java.sql.Time 47 | if (destClass.equals(java.sql.Time.class)) { 48 | return new java.sql.Time(value); 49 | } 50 | 51 | // java.sql.Timestamp 52 | if (destClass.equals(java.sql.Timestamp.class)) { 53 | return new java.sql.Timestamp(value); 54 | } 55 | } 56 | 57 | throw new BeanMappingException("Unsupported convert: [" + src + "," + destClass.getName() + "]"); 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/process/convertor/StringAndCommonConvertor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.process.convertor; 2 | 3 | import java.math.BigDecimal; 4 | import java.math.BigInteger; 5 | import java.util.Arrays; 6 | import java.util.HashSet; 7 | import java.util.Set; 8 | 9 | import com.alibaba.tamper.core.BeanMappingException; 10 | 11 | /** 12 | * string <-> common对象 之间的转化 13 | * 14 | *
 15 |  * common对象范围:8种Primitive和对应的Java类型,BigDecimal, BigInteger
 16 |  * 
 17 |  * 
18 | * 19 | * @author jianghang 2011-5-25 下午11:11:25 20 | */ 21 | public class StringAndCommonConvertor { 22 | 23 | /** 24 | * string -> common对象的转化 25 | */ 26 | public static class StringToCommon extends AbastactConvertor { 27 | 28 | protected static final Set TRUE_STRINGS = new HashSet(Arrays.asList(new String[] { "true", "on", "yes", "y" })); 29 | protected static final Set FALSE_STRINGS = new HashSet(Arrays.asList(new String[] { "false", "null", "nul", 30 | "nil", "off", "no", "n" })); 31 | 32 | protected Boolean booleanConvert(Object value) { 33 | if (value instanceof Boolean) { 34 | return (Boolean) value; 35 | } 36 | 37 | if (value instanceof Number) { 38 | return (Math.abs(((Number) value).doubleValue()) < Float.MIN_VALUE) ? Boolean.FALSE : Boolean.TRUE; 39 | } 40 | 41 | if (value instanceof String) { 42 | String strValue = ((String) value).trim(); 43 | try { 44 | return (Integer.parseInt(strValue) == 0) ? Boolean.FALSE : Boolean.TRUE; 45 | } catch (NumberFormatException e) { 46 | strValue = strValue.toLowerCase(); 47 | 48 | if (TRUE_STRINGS.contains(strValue)) { 49 | return Boolean.TRUE; 50 | } 51 | 52 | if (FALSE_STRINGS.contains(strValue)) { 53 | return Boolean.FALSE; 54 | } 55 | 56 | } 57 | } 58 | 59 | throw new BeanMappingException("Unsupported convert: [" + String.class + "," + Boolean.class.getName() 60 | + "]"); 61 | } 62 | 63 | protected Character charConvert(Object value) { 64 | if (value instanceof Character) { 65 | return (Character) value; 66 | } 67 | 68 | if (value instanceof Number) { 69 | return new Character((char) ((Number) value).intValue()); 70 | } 71 | 72 | if (value instanceof String) { 73 | String strValue = ((String) value).trim(); 74 | 75 | try { 76 | return new Character((char) Integer.parseInt(strValue)); 77 | } catch (NumberFormatException e) { 78 | } 79 | } 80 | 81 | throw new BeanMappingException("Unsupported convert: [" + String.class + "," + Character.class.getName() 82 | + "]"); 83 | } 84 | 85 | @Override 86 | public Object convert(Object src, Class destClass) { 87 | if (String.class.isInstance(src)) { // src必须是String 88 | String str = (String) src; 89 | if (destClass == Double.class || destClass == double.class) { 90 | return Double.valueOf(str); 91 | } 92 | 93 | if (destClass == Float.class || destClass == float.class) { 94 | return Float.valueOf(str); 95 | } 96 | 97 | if (destClass == Boolean.class || destClass == boolean.class) { 98 | return booleanConvert(str); 99 | } 100 | 101 | if (destClass == Integer.class || destClass == int.class) { 102 | return Integer.valueOf(str); 103 | } 104 | 105 | if (destClass == Short.class || destClass == short.class) { 106 | return Short.valueOf(str); 107 | } 108 | 109 | if (destClass == Long.class || destClass == long.class) { 110 | return Long.valueOf(str); 111 | } 112 | 113 | if (destClass == Byte.class || destClass == byte.class) { 114 | return Byte.valueOf(str); 115 | } 116 | 117 | if (destClass == Character.class || destClass == char.class) { 118 | return charConvert(str); // 只取第一个字符 119 | } 120 | 121 | if (destClass == BigDecimal.class) { 122 | return new BigDecimal(str); 123 | } 124 | 125 | if (destClass == BigInteger.class) { 126 | return new BigInteger(str); 127 | } 128 | } 129 | 130 | throw new BeanMappingException("Unsupported convert: [" + src + "," + destClass.getName() + "]"); 131 | } 132 | } 133 | } 134 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/process/convertor/StringAndDateConvertor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.process.convertor; 2 | 3 | import java.text.ParseException; 4 | import java.text.SimpleDateFormat; 5 | import java.util.Calendar; 6 | import java.util.Date; 7 | import java.util.GregorianCalendar; 8 | 9 | import com.alibaba.tamper.core.BeanMappingException; 10 | 11 | /** 12 | * string <-> Date/Calendar 之间的转化 13 | * 14 | * @author jianghang 2011-5-26 上午09:50:31 15 | */ 16 | public class StringAndDateConvertor { 17 | 18 | public static final String DAY_FORMAT = "yyyy-MM-dd"; 19 | public static final String TIME_FORMAT = "yyyy-MM-dd HH:mm:ss"; 20 | 21 | /** 22 | * string(格式为:"2010-10-01") -> Calendar 23 | */ 24 | public static class StringToDateDay extends AbastactConvertor { 25 | 26 | @Override 27 | public Object convert(Object src, Class destClass) { 28 | if (String.class.isInstance(src)) { // 必须是字符串 29 | try { 30 | return new SimpleDateFormat(DAY_FORMAT).parse((String) src); 31 | } catch (ParseException e) { 32 | throw new BeanMappingException("convert failed: [" + src + "," + destClass.getName() + "]", e); 33 | } 34 | } 35 | 36 | throw new BeanMappingException("Unsupported convert: [" + src + "," + destClass.getName() + "]"); 37 | } 38 | } 39 | 40 | /** 41 | * string(格式为:"2010-10-01 00:00:00") -> Date 42 | */ 43 | public static class StringToDateTime extends AbastactConvertor { 44 | 45 | @Override 46 | public Object convert(Object src, Class destClass) { 47 | if (String.class.isInstance(src)) { // 必须是字符串 48 | try { 49 | return new SimpleDateFormat(TIME_FORMAT).parse((String) src); 50 | } catch (ParseException e) { 51 | throw new BeanMappingException("convert failed: [" + src + "," + destClass.getName() + "]", e); 52 | } 53 | } 54 | 55 | throw new BeanMappingException("Unsupported convert: [" + src + "," + destClass.getName() + "]"); 56 | } 57 | 58 | } 59 | 60 | /** 61 | * Date -> string(格式为:"2010-10-01") 62 | */ 63 | public static class DateDayToString extends AbastactConvertor { 64 | 65 | @Override 66 | public Object convert(Object src, Class destClass) { 67 | if (Date.class.isInstance(src)) { // 必须是Date对象 68 | return new SimpleDateFormat(DAY_FORMAT).format((Date) src); 69 | } 70 | 71 | throw new BeanMappingException("Unsupported convert: [" + src + "," + destClass.getName() + "]"); 72 | } 73 | 74 | } 75 | 76 | /** 77 | * Date -> string(格式为:"2010-10-01 00:00:00") 78 | */ 79 | public static class DateTimeToString extends AbastactConvertor { 80 | 81 | @Override 82 | public Object convert(Object src, Class destClass) { 83 | if (Date.class.isInstance(src)) { // 必须是Date对象 84 | return new SimpleDateFormat(TIME_FORMAT).format((Date) src); 85 | } 86 | 87 | throw new BeanMappingException("Unsupported convert: [" + src + "," + destClass.getName() + "]"); 88 | } 89 | 90 | } 91 | 92 | /** 93 | * string(格式为:"2010-10-01") -> Calendar 94 | */ 95 | public static class StringToCalendarDay extends AbastactConvertor { 96 | 97 | @Override 98 | public Object convert(Object src, Class destClass) { 99 | if (String.class.isInstance(src)) { // 必须是字符串 100 | Date dest = (Date) new StringToDateDay().convert(src, Date.class); 101 | Calendar result = new GregorianCalendar(); 102 | result.setTime(dest); 103 | return result; 104 | } 105 | 106 | throw new BeanMappingException("Unsupported convert: [" + src + "," + destClass.getName() + "]"); 107 | } 108 | } 109 | 110 | /** 111 | * string(格式为:"2010-10-01 00:00:00") -> Calendar 112 | */ 113 | public static class StringToCalendarTime extends AbastactConvertor { 114 | 115 | @Override 116 | public Object convert(Object src, Class destClass) { 117 | if (String.class.isInstance(src)) { // 必须是字符串 118 | Date dest = (Date) new StringToDateTime().convert(src, Date.class); 119 | Calendar result = new GregorianCalendar(); 120 | result.setTime(dest); 121 | return result; 122 | } 123 | 124 | throw new BeanMappingException("Unsupported convert: [" + src + "," + destClass.getName() + "]"); 125 | } 126 | } 127 | 128 | /** 129 | * Calendar -> string(格式为:"2010-10-01") 130 | */ 131 | public static class CalendarDayToString extends AbastactConvertor { 132 | 133 | @Override 134 | public Object convert(Object src, Class destClass) { 135 | if (Calendar.class.isInstance(src)) { // 必须是Calendar 136 | Calendar ca = (Calendar) src; 137 | return new DateDayToString().convert(ca.getTime(), String.class); 138 | } 139 | 140 | throw new BeanMappingException("Unsupported convert: [" + src + "," + destClass.getName() + "]"); 141 | } 142 | } 143 | 144 | /** 145 | * Calendar -> string(格式为:"2010-10-01 00:00:00") 146 | */ 147 | public static class CalendarTimeToString extends AbastactConvertor { 148 | 149 | @Override 150 | public Object convert(Object src, Class destClass) { 151 | if (Calendar.class.isInstance(src)) { // 必须是Calendar 152 | Calendar ca = (Calendar) src; 153 | return new DateTimeToString().convert(ca.getTime(), String.class); 154 | } 155 | 156 | throw new BeanMappingException("Unsupported convert: [" + src + "," + destClass.getName() + "]"); 157 | } 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/process/convertor/StringAndEnumConvertor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.process.convertor; 2 | 3 | import com.alibaba.tamper.core.BeanMappingException; 4 | 5 | /** 6 | * string <-> Enum 之间的转化 7 | * 8 | * @author jianghang 2011-7-12 下午12:49:30 9 | */ 10 | public class StringAndEnumConvertor { 11 | 12 | /** 13 | * string -> Enum 对象的转化 14 | */ 15 | public static class StringToEnum extends AbastactConvertor { 16 | 17 | @Override 18 | public Object convert(Object src, Class destClass) { 19 | if (src instanceof String && destClass.isEnum()) { 20 | return Enum.valueOf(destClass, (String) src); 21 | } 22 | 23 | throw new BeanMappingException("Unsupported convert: [" + src.getClass() + "," + destClass.getName() + "]"); 24 | 25 | } 26 | } 27 | 28 | /** 29 | * Enum -> String 对象的转化 30 | */ 31 | public static class EnumToString extends AbastactConvertor { 32 | 33 | @Override 34 | public Object convert(Object src, Class destClass) { 35 | if (src.getClass().isEnum() && destClass == String.class) { 36 | return ((Enum) src).name(); // 返回定义的enum name 37 | } 38 | 39 | throw new BeanMappingException("Unsupported convert: [" + src.getClass() + "," + destClass.getName() + "]"); 40 | } 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/process/convertor/StringAndObjectConvertor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.process.convertor; 2 | 3 | /** 4 | * object <-> String 之间的转化器,目前只实现object -> String的转化 5 | * 6 | * @author jianghang 2011-5-25 下午10:26:30 7 | */ 8 | public class StringAndObjectConvertor { 9 | 10 | /** 11 | * object -> string 转化 12 | */ 13 | public static class ObjectToString extends AbastactConvertor { 14 | 15 | @Override 16 | public Object convert(Object src, Class destClass) { 17 | return src != null ? src.toString() : null; 18 | } 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/process/script/ScriptContext.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.process.script; 2 | 3 | /** 4 | * modelBuilder具体的上下文 5 | * 6 | *
 7 |  * 上下文中包含的内容:
 8 |  * 1.builder的目标model对象的引用
 9 |  * 2.data数据对象的引用
10 |  * 3.formatter的实例引用
11 |  * 
12 | * 13 | * @author jianghang 2011-5-20 下午03:43:14 14 | */ 15 | public interface ScriptContext { 16 | 17 | } 18 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/process/script/ScriptExecutor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.process.script; 2 | 3 | import java.util.Map; 4 | 5 | /** 6 | * script具体的执行器 7 | * 8 | * @author jianghang 2011-5-20 下午03:42:10 9 | */ 10 | public interface ScriptExecutor { 11 | 12 | /** 13 | * Generate a proper execute context for the executor. 14 | */ 15 | public ScriptContext genScriptContext(Map context); 16 | 17 | /** 18 | * 接受Map context上下文,执行script 19 | */ 20 | public Object evaluate(Map context, String script); 21 | 22 | /** 23 | * 接受ScriptContext上下文,执行script 24 | */ 25 | public Object evaluate(ScriptContext context, String script); 26 | 27 | public void disposeFunctions(); 28 | 29 | public void addFunction(String name, Object func); 30 | 31 | } 32 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/process/script/ScriptHelper.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.process.script; 2 | 3 | import java.io.BufferedReader; 4 | import java.io.InputStream; 5 | import java.io.InputStreamReader; 6 | import java.util.Map; 7 | import java.util.Map.Entry; 8 | 9 | import org.apache.commons.lang.StringUtils; 10 | 11 | import com.alibaba.tamper.core.helper.ReflectionHelper; 12 | import com.alibaba.tamper.process.script.jexl.JexlScriptExecutor; 13 | 14 | /** 15 | * script的function class操作helper类 16 | * 17 | * @author jianghang 2011-6-27 下午07:32:25 18 | */ 19 | public class ScriptHelper { 20 | 21 | private static final String DEFAULT_SCRIPT = JexlScriptExecutor.class.getName(); 22 | private static final String property = "BeanMapping.Script.Executor"; 23 | private static volatile ScriptHelper singleton = null; 24 | private volatile ScriptExecutor executor = null; 25 | 26 | public ScriptHelper(){ 27 | } 28 | 29 | /** 30 | * 单例方法 31 | */ 32 | public static ScriptHelper getInstance() { 33 | if (singleton == null) { 34 | synchronized (ScriptHelper.class) { 35 | if (singleton == null) { // double check 36 | singleton = new ScriptHelper(); 37 | } 38 | } 39 | } 40 | return singleton; 41 | } 42 | 43 | /** 44 | * @return 返回对应的{@linkplain ScriptExecutor} 45 | */ 46 | public ScriptExecutor getScriptExecutor() { 47 | if (executor == null) { 48 | synchronized (ScriptHelper.class) { 49 | if (executor == null) { 50 | executor = createScriptExecutor(); 51 | } 52 | } 53 | } 54 | 55 | return executor; 56 | } 57 | 58 | /** 59 | * 注册对应的function,并绑定为指定的name 60 | */ 61 | public void registerFunctionClass(String name, Object function) { 62 | getScriptExecutor().addFunction(name, function); 63 | } 64 | 65 | /** 66 | * 批量注册function 67 | */ 68 | public void batchRegisterFunctionClass(Map functions) { 69 | if (functions != null && functions.size() > 0) { 70 | for (Entry entry : functions.entrySet()) { 71 | registerFunctionClass(entry.getKey(), entry.getValue()); 72 | } 73 | } 74 | } 75 | 76 | /** 77 | * 创建ScriptExecutor 78 | * 79 | *
 80 |      * 1. 从jvm system property加载对应的classname
 81 |      * 2. 从META-INF/services/加载对应的classname
 82 |      * 
83 | */ 84 | private ScriptExecutor createScriptExecutor() { 85 | String className = null; 86 | ClassLoader loader = ScriptExecutor.class.getClassLoader(); 87 | 88 | // 1. try the JVM-instance-wide system property 89 | try { 90 | className = System.getProperty(property); 91 | } catch (RuntimeException e) { /* normally fails for applets */ 92 | } 93 | 94 | // 2. if that fails, try META-INF/services/ 95 | if (StringUtils.isEmpty(className)) { 96 | try { 97 | String service = "META-INF/services/" + property; 98 | InputStream in; 99 | BufferedReader reader; 100 | 101 | if (loader == null) { 102 | in = ClassLoader.getSystemResourceAsStream(service); 103 | } else { 104 | in = loader.getResourceAsStream(service); 105 | } 106 | 107 | if (in != null) { 108 | reader = new BufferedReader(new InputStreamReader(in, System.getProperty("file.encoding", "UTF-8"))); 109 | className = reader.readLine(); 110 | in.close(); 111 | } 112 | } catch (Exception e) { 113 | } 114 | } 115 | 116 | // 3. Distro-specific fallback 117 | if (className == null) { 118 | className = DEFAULT_SCRIPT; 119 | } 120 | 121 | Class clazz = ReflectionHelper.forName(className, loader); 122 | return (ScriptExecutor) ReflectionHelper.newInstance(clazz); 123 | } 124 | 125 | } 126 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/process/script/jexl/JexlScriptExecutor.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.process.script.jexl; 2 | 3 | import java.util.HashMap; 4 | import java.util.HashSet; 5 | import java.util.Map; 6 | import java.util.Set; 7 | 8 | import org.apache.commons.jexl2.Expression; 9 | import org.apache.commons.jexl2.Interpreter; 10 | import org.apache.commons.jexl2.JexlContext; 11 | import org.apache.commons.jexl2.JexlEngine; 12 | import org.apache.commons.jexl2.MapContext; 13 | import org.apache.commons.jexl2.parser.JexlNode; 14 | 15 | import com.alibaba.tamper.process.script.ScriptContext; 16 | import com.alibaba.tamper.process.script.ScriptExecutor; 17 | import com.alibaba.tamper.process.script.lifecyle.DisposableScript; 18 | import com.alibaba.tamper.process.script.lifecyle.InitializingScript; 19 | 20 | /** 21 | * Jexl的script实现 22 | * 23 | * @author jianghang 2011-5-25 下午08:08:45 24 | */ 25 | public class JexlScriptExecutor implements ScriptExecutor { 26 | 27 | private static final int DEFAULT_CACHE_SIZE = 1000; 28 | private ScriptJexlEngine engine; 29 | private Map functions; 30 | private int cacheSize = DEFAULT_CACHE_SIZE; 31 | 32 | public JexlScriptExecutor(){ 33 | initialize(); 34 | } 35 | 36 | /** 37 | * 初始化function 38 | */ 39 | public void initialize() { 40 | if (cacheSize <= 0) {// 不考虑cacheSize为0的情况,强制使用LRU cache机制 41 | cacheSize = DEFAULT_CACHE_SIZE; 42 | } 43 | 44 | functions = new HashMap(); 45 | engine = new ScriptJexlEngine(); 46 | engine.setCache(cacheSize); 47 | engine.setSilent(true); 48 | engine.setFunctions(functions); // 注册functions 49 | } 50 | 51 | public ScriptContext genScriptContext(Map context) { 52 | return new JexlScriptContext(context); 53 | } 54 | 55 | public Object evaluate(Map context, String script) { 56 | return evaluate(genScriptContext(context), script); 57 | } 58 | 59 | /** 60 | *
 61 |      * 1. 接受JexlScriptContext上下文
 62 |      * 2. script针对对应name下的script脚本
 63 |      * 
64 | */ 65 | public Object evaluate(ScriptContext context, String script) { 66 | Expression expr = engine.createExpression(script); 67 | return expr.evaluate((JexlContext) context); 68 | } 69 | 70 | // ============================ setter / getter ============================ 71 | 72 | public void setCacheSize(int cacheSize) { 73 | this.cacheSize = cacheSize; 74 | } 75 | 76 | public void addFunction(String name, Object obj) { 77 | this.functions.put(name, obj); 78 | } 79 | 80 | public void disposeFunctions() { 81 | engine.disposeUsedFunctions(); 82 | } 83 | 84 | } 85 | 86 | /** 87 | * 定义为Jexl context 88 | * 89 | * @author jianghang 2011-5-25 下午07:57:59 90 | */ 91 | class JexlScriptContext extends MapContext implements ScriptContext { 92 | 93 | public JexlScriptContext(Map map){ 94 | super(map); 95 | } 96 | } 97 | 98 | /** 99 | * 扩展jexl的实现,提供{@linkplain InitializingScript},{@linkplain DisposableScript}的管理 100 | */ 101 | class ScriptJexlEngine extends JexlEngine { 102 | 103 | // 记录script执行过程中使用过的function 104 | private ThreadLocal> usedFunctions = null; 105 | 106 | public ScriptJexlEngine(){ 107 | super(null, null, null, null); 108 | usedFunctions = new ThreadLocal>() { 109 | 110 | protected Set initialValue() { 111 | return new HashSet(); // 线程安全,不全同步 112 | } 113 | }; 114 | } 115 | 116 | protected Interpreter createInterpreter(JexlContext context) { 117 | if (context == null) { 118 | context = EMPTY_CONTEXT; 119 | } 120 | return new ScriptInterpreter(this, context); 121 | } 122 | 123 | class ScriptInterpreter extends Interpreter { 124 | 125 | public ScriptInterpreter(JexlEngine jexl, JexlContext aContext){ 126 | super(jexl, aContext); 127 | } 128 | 129 | protected Object resolveNamespace(String prefix, JexlNode node) { 130 | Object result = super.resolveNamespace(prefix, node); 131 | if (result != null) { 132 | boolean contains = usedFunctions.get().add(result);// 添加到使用记录中 133 | if (contains && InitializingScript.class.isAssignableFrom(result.getClass())) {// 第一次添加 134 | ((InitializingScript) result).initial();// 回调 135 | } 136 | } 137 | return result; 138 | } 139 | } 140 | 141 | public void disposeUsedFunctions() { 142 | try { 143 | Set functions = usedFunctions.get(); 144 | for (Object function : functions) { 145 | if (function != null && DisposableScript.class.isAssignableFrom(function.getClass())) { 146 | ((DisposableScript) function).dispose();// 回调 147 | } 148 | } 149 | } finally { 150 | usedFunctions.set(new HashSet());// 清空 151 | } 152 | } 153 | 154 | } 155 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/process/script/lifecyle/DisposableScript.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.process.script.lifecyle; 2 | 3 | /** 4 | * 支持Disposable的script接口,在一次Mapping完成后进行回调,完成数据清理动作 5 | * 6 | * @author jianghang 2011-11-23 下午04:39:37 7 | */ 8 | public interface DisposableScript { 9 | 10 | public void dispose(); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/java/com/alibaba/tamper/process/script/lifecyle/InitializingScript.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.process.script.lifecyle; 2 | 3 | /** 4 | * 支持Initializing的script接口,在一次Mapping之前进行回调初始化 5 | * 6 | * @author jianghang 2011-11-23 下午04:39:37 7 | */ 8 | public interface InitializingScript { 9 | 10 | public void initial(); 11 | } 12 | -------------------------------------------------------------------------------- /src/main/resources/mapping.properties: -------------------------------------------------------------------------------- 1 | valueProcess.script = com.alibaba.tamper.process.ScriptValueProcess 2 | valueProcess.defaultValue = com.alibaba.tamper.process.DefaultValueValueProcess 3 | valueProcess.convertor = com.alibaba.tamper.process.ConvertorValueProcess 4 | valueProcess.behavior = com.alibaba.tamper.process.BehaviorValueProcess 5 | valueProcess.debug = com.alibaba.tamper.process.DebugValueProcess 6 | valueProcess.beanCreator = com.alibaba.tamper.process.BeanCreatorValueProcess 7 | 8 | beanMapping.valueProcess.list = script,defaultValue,convertor,beanCreator,behavior,debug 9 | beanMap.valueProcess.list = 10 | beanCopy.valueProcess.list = convertor 11 | 12 | uberspect.impl = com.alibaba.tamper.core.introspect.UberspectImpl -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/BeanCopyTest.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper; 2 | 3 | import java.math.BigDecimal; 4 | 5 | import junit.framework.TestCase; 6 | 7 | import org.junit.Test; 8 | 9 | import com.alibaba.tamper.object.NestedSrcMappingObject; 10 | import com.alibaba.tamper.object.NestedTargetMappingObject; 11 | import com.alibaba.tamper.object.SrcMappingObject; 12 | import com.alibaba.tamper.object.TargetMappingObject; 13 | 14 | /** 15 | * bean copy的相关测试 16 | * 17 | * @author jianghang 2011-5-29 上午01:08:46 18 | */ 19 | public class BeanCopyTest extends TestCase { 20 | 21 | public BeanCopy srcCopyer = BeanCopy.create(SrcMappingObject.class, TargetMappingObject.class); 22 | public BeanCopy targetCopyer = BeanCopy.create(TargetMappingObject.class, SrcMappingObject.class); 23 | public BeanCopy nestedSrcCopyer = BeanCopy.create(NestedSrcMappingObject.class, NestedTargetMappingObject.class); 24 | public BeanCopy nestedTargetCopyer = BeanCopy.create(NestedTargetMappingObject.class, NestedSrcMappingObject.class); 25 | 26 | @Test 27 | public void testCopy_ok() { 28 | SrcMappingObject srcRef = new SrcMappingObject(); 29 | srcRef.setIntegerValue(1); 30 | srcRef.setIntValue(1); 31 | srcRef.setName("ljh"); 32 | srcRef.setStart(true); 33 | 34 | // NestedSrcMappingObject nestedSrcRef = new NestedSrcMappingObject(); 35 | // nestedSrcRef.setBigDecimalValue(BigDecimal.ONE); 36 | // srcRef.setMapping(nestedSrcRef); 37 | 38 | TargetMappingObject targetRef = new TargetMappingObject();// 测试一下mapping到一个Object对象 39 | srcCopyer.copy(srcRef, targetRef); 40 | assertEquals(targetRef.getIntegerValue(), srcRef.getIntegerValue()); 41 | assertEquals(targetRef.getIntValue(), srcRef.getIntValue()); 42 | assertNull(targetRef.getTargetName());// 为null,因为属性不匹配 43 | assertEquals(targetRef.isStart(), srcRef.isStart()); 44 | 45 | SrcMappingObject newSrcRef = new SrcMappingObject();// 反过来再mapping一次 46 | targetCopyer.copy(targetRef, newSrcRef); 47 | assertEquals(newSrcRef.getIntegerValue(), targetRef.getIntegerValue()); 48 | assertEquals(newSrcRef.getIntValue(), targetRef.getIntValue()); 49 | assertNull(newSrcRef.getName());// 为null,因为属性不匹配 50 | assertEquals(newSrcRef.isStart(), targetRef.isStart()); 51 | } 52 | 53 | @Test 54 | public void testSimpleCopy_ok() { 55 | NestedSrcMappingObject nestedSrcRef = new NestedSrcMappingObject(); 56 | nestedSrcRef.setBigDecimalValue(BigDecimal.ONE); 57 | nestedSrcRef.setName("ljh"); 58 | 59 | NestedTargetMappingObject nestedTargetRef = new NestedTargetMappingObject();// 测试一下mapping到一个Object对象 60 | nestedSrcCopyer.copy(nestedSrcRef, nestedTargetRef); 61 | assertNull(nestedTargetRef.getValue());// 属性不同,类型也不同 62 | assertEquals(nestedTargetRef.getName(), nestedSrcRef.getName()); 63 | 64 | NestedSrcMappingObject newNestedSrcRef = new NestedSrcMappingObject();// 反过来再mapping一次 65 | nestedTargetCopyer.copy(nestedTargetRef, newNestedSrcRef); 66 | assertNull(newNestedSrcRef.getBigDecimalValue());// 属性不同,类型也不同 67 | assertEquals(newNestedSrcRef.getName(), nestedTargetRef.getName()); 68 | 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/BeanMapTest.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper; 2 | 3 | import java.math.BigDecimal; 4 | import java.util.Map; 5 | 6 | import junit.framework.TestCase; 7 | 8 | import org.junit.Test; 9 | 10 | import com.alibaba.tamper.object.NestedSrcMappingObject; 11 | import com.alibaba.tamper.object.SrcMappingObject; 12 | 13 | /** 14 | * @author jianghang 2011-5-29 上午01:08:39 15 | */ 16 | public class BeanMapTest extends TestCase { 17 | 18 | public BeanMap beanMap = BeanMap.create(SrcMappingObject.class); 19 | 20 | @Test 21 | public void testDescribe_Populate_ok() { 22 | SrcMappingObject srcRef = new SrcMappingObject(); 23 | srcRef.setIntegerValue(1); 24 | srcRef.setIntValue(1); 25 | srcRef.setName("ljh"); 26 | srcRef.setStart(true); 27 | 28 | NestedSrcMappingObject nestedSrcRef = new NestedSrcMappingObject(); 29 | nestedSrcRef.setBigDecimalValue(BigDecimal.ONE); 30 | srcRef.setMapping(nestedSrcRef); 31 | 32 | Map map = beanMap.describe(srcRef); 33 | assertEquals(map.get("integerValue"), srcRef.getIntegerValue()); 34 | assertEquals(map.get("intValue"), srcRef.getIntValue()); 35 | assertEquals(map.get("name"), srcRef.getName()); 36 | assertEquals(map.get("start"), srcRef.isStart()); 37 | assertNotNull(map.get("mapping")); 38 | NestedSrcMappingObject nested = (NestedSrcMappingObject) map.get("mapping"); 39 | assertEquals(srcRef.getMapping(), nested);// 没有做递归的describe 40 | // assertEquals(nested.get("bigDecimalValue"), nestedSrcRef.getBigDecimalValue()); 41 | // assertEquals(nested.get("name"), null);// 没有设置,为null 42 | 43 | SrcMappingObject newSrcRef = new SrcMappingObject();// 反过来再mapping一次 44 | beanMap.populate(newSrcRef, map); 45 | assertEquals(map.get("integerValue"), newSrcRef.getIntegerValue()); 46 | assertEquals(map.get("intValue"), newSrcRef.getIntValue()); 47 | assertEquals(map.get("name"), newSrcRef.getName()); 48 | assertEquals(map.get("start"), newSrcRef.isStart()); 49 | assertNotNull(map.get("mapping")); 50 | NestedSrcMappingObject newNested = (NestedSrcMappingObject) newSrcRef.getMapping(); 51 | assertEquals(map.get("mapping"), newNested);// 没有做递归的describe 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/ConfigTest.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper; 2 | 3 | import java.util.HashMap; 4 | 5 | import junit.framework.Assert; 6 | import junit.framework.TestCase; 7 | 8 | import org.apache.commons.lang.builder.ToStringBuilder; 9 | import org.apache.commons.lang.builder.ToStringStyle; 10 | import org.junit.Test; 11 | 12 | import com.alibaba.tamper.core.config.BeanMappingBehavior; 13 | import com.alibaba.tamper.core.config.BeanMappingConfigHelper; 14 | import com.alibaba.tamper.core.config.BeanMappingField; 15 | import com.alibaba.tamper.core.config.BeanMappingObject; 16 | import com.alibaba.tamper.object.SrcMappingObject; 17 | import com.alibaba.tamper.object.TargetMappingObject; 18 | 19 | /** 20 | * @author jianghang 2011-5-27 上午09:26:38 21 | */ 22 | public class ConfigTest extends TestCase { 23 | 24 | @Test 25 | public void testFileParse() { 26 | String file = "mapping/config.xml"; 27 | BeanMappingConfigHelper.getInstance().registerConfig(file); 28 | BeanMappingObject object = BeanMappingConfigHelper.getInstance().getBeanMappingObject(HashMap.class, 29 | HashMap.class); 30 | assertNull(object); 31 | object = BeanMappingConfigHelper.getInstance().getBeanMappingObject("testConfig"); 32 | printObject(object); 33 | assertNotNull(object); 34 | BeanMappingBehavior globalBehavior = BeanMappingConfigHelper.getInstance().getGlobalBehavior(); 35 | Assert.assertEquals(globalBehavior.isMappingNullValue(), true); 36 | Assert.assertEquals(globalBehavior.isMappingEmptyStrings(), true); 37 | Assert.assertEquals(globalBehavior.isDebug(), false); 38 | Assert.assertEquals(globalBehavior.isTrimStrings(), true); 39 | 40 | BeanMappingBehavior beanBehavior = object.getBehavior(); 41 | Assert.assertEquals(beanBehavior.isMappingNullValue(), false);// 覆盖了global 42 | Assert.assertEquals(beanBehavior.isDebug(), true); // 覆盖了global 43 | Assert.assertEquals(beanBehavior.isMappingEmptyStrings(), true); // 继承了global 44 | Assert.assertEquals(beanBehavior.isTrimStrings(), true); // 继承了global 45 | 46 | BeanMappingField field = object.getBeanFields().get(0); 47 | BeanMappingBehavior fieldBehavior = field.getBehavior(); 48 | Assert.assertEquals(fieldBehavior.isMappingNullValue(), true);// 覆盖了bean 49 | Assert.assertEquals(fieldBehavior.isDebug(), true); // 继承了bean 50 | Assert.assertEquals(fieldBehavior.isMappingEmptyStrings(), true); // 继承了bean 51 | Assert.assertEquals(fieldBehavior.isTrimStrings(), true); // 继承了bean 52 | 53 | } 54 | 55 | @Test 56 | public void testClassParse() { 57 | Class srcClass = SrcMappingObject.class; 58 | Class targetClass = TargetMappingObject.class; 59 | BeanMappingObject object = BeanMappingConfigHelper.getInstance().getBeanMappingObject(srcClass, targetClass, 60 | true);// 自动注册 61 | assertNotNull(object); 62 | printObject(object); 63 | } 64 | 65 | private void printObject(BeanMappingObject object) { 66 | System.out.println(ToStringBuilder.reflectionToString(object, ToStringStyle.MULTI_LINE_STYLE)); 67 | for (BeanMappingField field : object.getBeanFields()) { 68 | System.out.println(ToStringBuilder.reflectionToString(field, ToStringStyle.MULTI_LINE_STYLE)); 69 | } 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/InheritObjectMappingTest.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper; 2 | 3 | import java.math.BigInteger; 4 | import java.util.HashMap; 5 | import java.util.Map; 6 | 7 | import junit.framework.Assert; 8 | import junit.framework.TestCase; 9 | 10 | import org.junit.Before; 11 | import org.junit.Test; 12 | 13 | import com.alibaba.tamper.core.builder.BeanMappingBuilder; 14 | import com.alibaba.tamper.core.config.BeanMappingConfigHelper; 15 | import com.alibaba.tamper.core.config.BeanMappingConfigRespository; 16 | import com.alibaba.tamper.object.inherit.FirstObject; 17 | import com.alibaba.tamper.object.inherit.TwoObject; 18 | import com.alibaba.tamper.process.script.ScriptHelper; 19 | import com.alibaba.tamper.script.CustomFunctionClass; 20 | 21 | /** 22 | * 测试一下带继承关系的属性,映射到一平面上 23 | * 24 | * @author jianghang 2011-6-22 下午03:42:51 25 | */ 26 | public class InheritObjectMappingTest extends TestCase { 27 | 28 | @Before 29 | public void setUp() { 30 | try { 31 | // 清空下repository下的数据 32 | TestUtils.setField(BeanMappingConfigHelper.getInstance(), "repository", new BeanMappingConfigRespository()); 33 | 34 | ScriptHelper.getInstance().registerFunctionClass("customFunction", new CustomFunctionClass()); 35 | } catch (Exception e) { 36 | Assert.fail(); 37 | } 38 | } 39 | 40 | @Test 41 | public void testFlat() { 42 | BeanMappingBuilder builder = new BeanMappingBuilder() { 43 | 44 | protected void configure() { 45 | behavior().debug(true);// 设置行为 46 | mapping(TwoObject.class, HashMap.class); 47 | fields(srcField("name").locatorClass(FirstObject.class), targetField("name"));// name从父类中获取 48 | fields(srcField("firstValue").locatorClass(FirstObject.class), targetField("firstValue"));// 也从父类中获取 49 | fields(srcField("twoValue"), targetField("twoValue")); 50 | } 51 | 52 | }; 53 | 54 | BeanMapping mapping = new BeanMapping(builder); 55 | TwoObject src = new TwoObject("one", "two"); 56 | src.setFirstValue(10); 57 | src.setTwoValue(BigInteger.TEN); 58 | 59 | Map dest = new HashMap(); 60 | mapping.mapping(src, dest); 61 | assertEquals(dest.get("name"), "two"); // 类的多台决定了,针对src调用getName()方法会取到子类的方法 62 | assertEquals(dest.get("firstValue"), Integer.valueOf(10)); 63 | assertEquals(dest.get("twoValue"), BigInteger.TEN); 64 | } 65 | 66 | @Test 67 | public void testLevel() { 68 | BeanMappingBuilder firstBuilder = new BeanMappingBuilder() { 69 | 70 | protected void configure() { 71 | behavior().debug(true);// 设置行为 72 | mapping(FirstObject.class, HashMap.class); 73 | fields(srcField("firstValue"), targetField("firstValue")); 74 | } 75 | 76 | }; 77 | 78 | BeanMappingBuilder twoBuilder = new BeanMappingBuilder() { 79 | 80 | protected void configure() { 81 | behavior().debug(true);// 设置行为 82 | mapping(TwoObject.class, HashMap.class); 83 | fields(srcField("twoValue"), targetField("twoValue")); 84 | fields(srcField("this", FirstObject.class), targetField("firstMap")).recursiveMapping(true).script( 85 | "customFunction:newHashMap()"); 86 | } 87 | 88 | }; 89 | 90 | BeanMappingConfigHelper.getInstance().register(firstBuilder); 91 | BeanMapping mapping = new BeanMapping(twoBuilder); 92 | TwoObject src = new TwoObject("one", "two"); 93 | src.setFirstValue(10); 94 | src.setTwoValue(BigInteger.TEN); 95 | 96 | Map dest = new HashMap(); 97 | mapping.mapping(src, dest); 98 | assertEquals(dest.get("twoValue"), BigInteger.TEN); 99 | assertEquals(((Map) dest.get("firstMap")).get("firstValue"), Integer.valueOf(10)); 100 | } 101 | 102 | @Test 103 | public void testExchange() { 104 | BeanMappingBuilder builder = new BeanMappingBuilder() { 105 | 106 | protected void configure() { 107 | behavior().debug(true);// 设置行为 108 | mapping(TwoObject.class, TwoObject.class); 109 | // firstValue的值设置给twoValue 110 | fields(srcField("firstValue").locatorClass(FirstObject.class), 111 | targetField("twoValue").locatorClass(TwoObject.class)); 112 | // twoValue的值设置给firstValue 113 | fields(srcField("twoValue").locatorClass(TwoObject.class), 114 | targetField("firstValue").locatorClass(FirstObject.class)); 115 | } 116 | 117 | }; 118 | 119 | BeanMapping mapping = new BeanMapping(builder); 120 | TwoObject src = new TwoObject("one", "two"); 121 | src.setFirstValue(11); 122 | src.setTwoValue(BigInteger.valueOf(12)); 123 | 124 | TwoObject dest = new TwoObject("one1", "two2"); 125 | 126 | mapping.mapping(src, dest); 127 | assertEquals(dest.getName(), "two2"); // 类的多台决定了,针对src调用getName()方法会取到子类的方法 128 | assertEquals(dest.getFirstValue(), 12); 129 | assertEquals(dest.getTwoValue(), BigInteger.valueOf(11)); 130 | } 131 | } 132 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/TestUtils.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper; 2 | 3 | import java.lang.reflect.Field; 4 | import java.lang.reflect.Method; 5 | 6 | import org.springframework.util.ReflectionUtils; 7 | 8 | /** 9 | * 提供常见的测试方法 10 | * 11 | * @author jianghang 2011-1-30 上午11:15:54 12 | */ 13 | public class TestUtils { 14 | 15 | /** 16 | * 获取对应属性的值 17 | * 18 | * @param obj 19 | * @param fieldName 20 | * @return 21 | */ 22 | public static Object getField(Object obj, String fieldName) { 23 | Field field = ReflectionUtils.findField(obj.getClass(), fieldName); 24 | ReflectionUtils.makeAccessible(field); 25 | return ReflectionUtils.getField(field, obj); 26 | } 27 | 28 | /** 29 | * 设置对应参数的值 30 | * 31 | * @param target 32 | * @param methodName 33 | * @param args 34 | * @return 35 | * @throws Exception 36 | */ 37 | public static void setField(Object target, String fieldName, Object args) throws Exception { 38 | // 查找对应的方法 39 | Field field = ReflectionUtils.findField(target.getClass(), fieldName); 40 | ReflectionUtils.makeAccessible(field); 41 | ReflectionUtils.setField(field, target, args); 42 | } 43 | 44 | /** 45 | * 调用方法,可以是一些私有方法 46 | * 47 | * @param target 48 | * @param methodName 49 | * @param args 50 | * @return 51 | * @throws Exception 52 | */ 53 | public static Object invokeMethod(Object target, String methodName, Object... args) throws Exception { 54 | Method method = null; 55 | // 查找对应的方法 56 | if (args == null || args.length == 0) { 57 | method = ReflectionUtils.findMethod(target.getClass(), methodName); 58 | } else { 59 | Class[] argsClass = new Class[args.length]; 60 | for (int i = 0; i < args.length; i++) { 61 | argsClass[i] = args[i].getClass(); 62 | } 63 | method = ReflectionUtils.findMethod(target.getClass(), methodName, argsClass); 64 | } 65 | ReflectionUtils.makeAccessible(method); 66 | 67 | if (args == null || args.length == 0) { 68 | return ReflectionUtils.invokeMethod(method, target); 69 | } else { 70 | return ReflectionUtils.invokeMethod(method, target, args); 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/builder/BeanMappingBuilderTest.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.builder; 2 | 3 | import java.util.ArrayList; 4 | import java.util.HashMap; 5 | import java.util.HashSet; 6 | 7 | import junit.framework.TestCase; 8 | 9 | import com.alibaba.tamper.core.builder.BeanMappingBuilder; 10 | import com.alibaba.tamper.core.config.BeanMappingBehavior; 11 | import com.alibaba.tamper.core.config.BeanMappingConfigHelper; 12 | import com.alibaba.tamper.core.config.BeanMappingField; 13 | import com.alibaba.tamper.core.config.BeanMappingObject; 14 | import com.alibaba.tamper.process.convertor.StringAndCommonConvertor.StringToCommon; 15 | 16 | /** 17 | * @author jianghang 2011-6-22 上午10:57:00 18 | */ 19 | public class BeanMappingBuilderTest extends TestCase { 20 | 21 | public void testSimpleBuilder() { 22 | BeanMappingBuilder builder = new BeanMappingBuilder() { 23 | 24 | protected void configure() { 25 | behavior(true, false, false, true);// 设置行为 26 | mapping(HashMap.class, HashMap.class).debug(true).mappingEmptyStrings(false).mappingNullValue(false).trimStrings( 27 | true); 28 | fields(srcField("one", String.class), targetField("oneOther", String.class)).debug(true).mappingEmptyStrings( 29 | false).mappingNullValue( 30 | false).trimStrings( 31 | true); 32 | fields(srcField("two").locatorClass(ArrayList.class).componentClasses(String.class), 33 | targetField("twoOther")); 34 | } 35 | 36 | }; 37 | 38 | BeanMappingObject object = builder.get(); 39 | assertNotNull(object); 40 | assertEquals(object.getBeanFields().size(), 2); 41 | 42 | } 43 | 44 | public void testBehavior() { 45 | BeanMappingBuilder builder = new BeanMappingBuilder() { 46 | 47 | protected void configure() { 48 | behavior().debug(true).mappingEmptyStrings(false).mappingNullValue(false).trimStrings(true);// 设置行为 49 | mapping(HashMap.class, HashMap.class).debug(false).mappingEmptyStrings(true); 50 | fields(srcField("one"), targetField("oneOther")).mappingEmptyStrings(false).trimStrings(false); 51 | } 52 | 53 | }; 54 | 55 | BeanMappingObject object = builder.get(); 56 | assertNotNull(object); 57 | // 验证bean behavior 58 | BeanMappingBehavior objectBehavior = object.getBehavior(); 59 | assertEquals(objectBehavior.isDebug(), false); // 覆盖 60 | assertEquals(objectBehavior.isMappingEmptyStrings(), true);// 覆盖 61 | assertEquals(objectBehavior.isMappingNullValue(), false); // 继承 62 | assertEquals(objectBehavior.isTrimStrings(), true); // 继承 63 | // 验证field behavior 64 | BeanMappingBehavior fieldBehavior = object.getBeanFields().get(0).getBehavior(); 65 | assertEquals(fieldBehavior.isDebug(), false); // 继承 66 | assertEquals(fieldBehavior.isMappingEmptyStrings(), false);// 覆盖 67 | assertEquals(fieldBehavior.isMappingNullValue(), false); // 继承 68 | assertEquals(fieldBehavior.isTrimStrings(), false); // 覆盖 69 | } 70 | 71 | public void testConfig() { 72 | BeanMappingBuilder builder = new BeanMappingBuilder() { 73 | 74 | protected void configure() { 75 | mapping(HashMap.class, HashMap.class).batch(false).reversable(true).keys("src", "target"); 76 | fields(srcField("one"), targetField("oneOther")).convertor("convertor").defaultValue("ljh"); 77 | fields(srcField("two").clazz(String.class), targetField("twoOther")).script("1+2").convertor( 78 | StringToCommon.class); 79 | fields(srcField("three").clazz(ArrayList.class), targetField("threeOther").clazz(HashSet.class)).recursiveMapping( 80 | true); 81 | } 82 | 83 | }; 84 | 85 | BeanMappingObject object = builder.get(); 86 | assertNotNull(object); 87 | assertEquals(object.getBeanFields().size(), 3); 88 | assertEquals(object.isBatch(), false); 89 | assertEquals(object.isReversable(), true); 90 | assertEquals(object.getSrcKey(), "src"); 91 | assertEquals(object.getTargetKey(), "target"); 92 | assertEquals(object.getSrcClass(), HashMap.class); 93 | assertEquals(object.getTargetClass(), HashMap.class); 94 | 95 | BeanMappingField one = object.getBeanFields().get(0); 96 | assertEquals(one.getConvertor(), "convertor"); 97 | assertEquals(one.getDefaultValue(), "ljh"); 98 | assertEquals(one.getSrcField().getName(), "one"); 99 | assertEquals(one.getTargetField().getName(), "oneOther"); 100 | 101 | BeanMappingField two = object.getBeanFields().get(1); 102 | assertEquals(two.getConvertorClass(), StringToCommon.class); 103 | assertEquals(two.getScript(), "1+2"); 104 | assertEquals(two.getSrcField().getName(), "two"); 105 | assertEquals(two.getSrcField().getClazz(), String.class); 106 | assertEquals(two.getTargetField().getName(), "twoOther"); 107 | 108 | BeanMappingField three = object.getBeanFields().get(2); 109 | assertEquals(three.getSrcField().getName(), "three"); 110 | assertEquals(three.getSrcField().getClazz(), ArrayList.class); 111 | assertEquals(three.getTargetField().getName(), "threeOther"); 112 | assertEquals(three.getTargetField().getClazz(), HashSet.class); 113 | assertEquals(three.isMapping(), true); 114 | 115 | } 116 | 117 | public void testRegister() { 118 | BeanMappingBuilder builder = new BeanMappingBuilder() { 119 | 120 | protected void configure() { 121 | mapping(HashMap.class, HashMap.class); 122 | fields(srcField("one"), targetField("oneOther")); 123 | } 124 | 125 | }; 126 | 127 | BeanMappingConfigHelper.getInstance().register(builder); // 进行注册 128 | 129 | BeanMappingObject object = BeanMappingConfigHelper.getInstance().getBeanMappingObject(HashMap.class, 130 | HashMap.class); 131 | 132 | assertNotNull(object); 133 | 134 | } 135 | } 136 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/convertor/ConvertorModel.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.convertor; 2 | 3 | import java.math.BigDecimal; 4 | 5 | /** 6 | * @author jianghang 2011-6-21 下午09:49:29 7 | */ 8 | public class ConvertorModel implements Comparable { 9 | 10 | private int i; 11 | private Integer integer; 12 | private BigDecimal bigDecimal; 13 | 14 | public int getI() { 15 | return i; 16 | } 17 | 18 | public void setI(int i) { 19 | this.i = i; 20 | } 21 | 22 | public Integer getInteger() { 23 | return integer; 24 | } 25 | 26 | public void setInteger(Integer integer) { 27 | this.integer = integer; 28 | } 29 | 30 | public BigDecimal getBigDecimal() { 31 | return bigDecimal; 32 | } 33 | 34 | public void setBigDecimal(BigDecimal bigDecimal) { 35 | this.bigDecimal = bigDecimal; 36 | } 37 | 38 | @Override 39 | public String toString() { 40 | return "ConvertorModel [bigDecimal=" + bigDecimal + ", i=" + i + ", integer=" + integer + "]"; 41 | } 42 | 43 | /* 44 | * (non-Javadoc) 45 | * @see java.lang.Comparable#compareTo(java.lang.Object) 46 | */ 47 | @Override 48 | public int compareTo(Object o) { 49 | if (o instanceof ConvertorModel) { 50 | return ((ConvertorModel) o).getI(); 51 | } 52 | 53 | return -1; 54 | } 55 | 56 | } 57 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/convertor/ConvertorOtherModel.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.convertor; 2 | 3 | import java.math.BigDecimal; 4 | 5 | /** 6 | * @author jianghang 2011-6-21 下午09:50:33 7 | */ 8 | public class ConvertorOtherModel implements Comparable { 9 | 10 | private int i; 11 | private Integer integer; 12 | private BigDecimal bigDecimal; 13 | 14 | public int getI() { 15 | return i; 16 | } 17 | 18 | public void setI(int i) { 19 | this.i = i; 20 | } 21 | 22 | public Integer getInteger() { 23 | return integer; 24 | } 25 | 26 | public void setInteger(Integer integer) { 27 | this.integer = integer; 28 | } 29 | 30 | public BigDecimal getBigDecimal() { 31 | return bigDecimal; 32 | } 33 | 34 | public void setBigDecimal(BigDecimal bigDecimal) { 35 | this.bigDecimal = bigDecimal; 36 | } 37 | 38 | @Override 39 | public String toString() { 40 | return "ConvertorOtherModel [bigDecimal=" + bigDecimal + ", i=" + i + ", integer=" + integer + "]"; 41 | } 42 | 43 | /* 44 | * (non-Javadoc) 45 | * @see java.lang.Comparable#compareTo(java.lang.Object) 46 | */ 47 | @Override 48 | public int compareTo(Object o) { 49 | if (o instanceof ConvertorOtherModel) { 50 | return ((ConvertorOtherModel) o).getI(); 51 | } 52 | 53 | return -1; 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/convertor/DateAndSqlDateTest.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.convertor; 2 | 3 | import java.util.Calendar; 4 | import java.util.Date; 5 | 6 | import junit.framework.TestCase; 7 | 8 | import org.junit.Test; 9 | 10 | import com.alibaba.tamper.process.convertor.Convertor; 11 | import com.alibaba.tamper.process.convertor.ConvertorHelper; 12 | 13 | public class DateAndSqlDateTest extends TestCase { 14 | 15 | private ConvertorHelper helper = new ConvertorHelper(); 16 | 17 | @Test 18 | public void testDateAndSqlDate() { 19 | Calendar c1 = Calendar.getInstance(); 20 | c1.set(2010, 10 - 1, 01, 23, 59, 59); 21 | c1.set(Calendar.MILLISECOND, 0); 22 | Date timeDate = c1.getTime(); 23 | 24 | Convertor dateToSql = helper.getConvertor(Date.class, java.sql.Date.class); 25 | java.sql.Date sqlDate = (java.sql.Date) dateToSql.convert(timeDate, java.sql.Date.class); 26 | assertNotNull(sqlDate); 27 | 28 | java.sql.Time sqlTime = (java.sql.Time) dateToSql.convert(timeDate, java.sql.Time.class); 29 | assertNotNull(sqlTime); 30 | 31 | java.sql.Timestamp sqlTimestamp = (java.sql.Timestamp) dateToSql.convert(timeDate, java.sql.Timestamp.class); 32 | assertNotNull(sqlTimestamp); 33 | 34 | Convertor sqlToDate = helper.getConvertor(java.sql.Date.class, Date.class); 35 | Date date = (Date) sqlToDate.convert(sqlDate, Date.class); 36 | assertEquals(timeDate, date); 37 | 38 | date = (Date) sqlToDate.convert(sqlTime, Date.class); 39 | assertEquals(timeDate, date); 40 | 41 | date = (Date) sqlToDate.convert(sqlTimestamp, Date.class); 42 | assertEquals(timeDate, date); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/convertor/StringAndEnumTest.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.convertor; 2 | 3 | import junit.framework.TestCase; 4 | 5 | import org.junit.Test; 6 | 7 | import com.alibaba.tamper.process.convertor.Convertor; 8 | import com.alibaba.tamper.process.convertor.ConvertorHelper; 9 | 10 | /** 11 | * @author jianghang 2011-7-12 下午01:04:33 12 | */ 13 | public class StringAndEnumTest extends TestCase { 14 | 15 | private ConvertorHelper helper = new ConvertorHelper(); 16 | 17 | @Test 18 | public void testStringAndEnum() { 19 | Convertor enumToString = helper.getConvertor(TestEnum.class, String.class); 20 | Convertor stringtoEnum = helper.getConvertor(String.class, TestEnum.class); 21 | String VALUE = "TWO"; 22 | 23 | Object str = enumToString.convert(TestEnum.TWO, String.class); // 数字 24 | assertEquals(str, VALUE); 25 | Object enumobj = stringtoEnum.convert(VALUE, TestEnum.class); // BigDecimal 26 | assertEquals(enumobj, TestEnum.TWO); 27 | } 28 | 29 | public static enum TestEnum { 30 | ONE, TWO, THREE; 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/object/NestedSrcMappingObject.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.object; 2 | 3 | import java.math.BigDecimal; 4 | 5 | import org.apache.commons.lang.builder.ToStringBuilder; 6 | import org.apache.commons.lang.builder.ToStringStyle; 7 | 8 | /** 9 | * @author jianghang 2011-5-27 上午11:30:21 10 | */ 11 | public class NestedSrcMappingObject { 12 | 13 | private String name; 14 | private BigDecimal bigDecimalValue; 15 | 16 | public String getName() { 17 | return name; 18 | } 19 | 20 | public void setName(String name) { 21 | this.name = name; 22 | } 23 | 24 | public BigDecimal getBigDecimalValue() { 25 | return bigDecimalValue; 26 | } 27 | 28 | public void setBigDecimalValue(BigDecimal bigDecimalValue) { 29 | this.bigDecimalValue = bigDecimalValue; 30 | } 31 | 32 | @Override 33 | public String toString() { 34 | return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/object/NestedTargetMappingObject.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.object; 2 | 3 | import org.apache.commons.lang.builder.ToStringBuilder; 4 | import org.apache.commons.lang.builder.ToStringStyle; 5 | 6 | /** 7 | * @author jianghang 2011-5-27 上午11:30:21 8 | */ 9 | public class NestedTargetMappingObject { 10 | 11 | private String name; 12 | private String value; 13 | 14 | public String getName() { 15 | return name; 16 | } 17 | 18 | public void setName(String name) { 19 | this.name = name; 20 | } 21 | 22 | public String getValue() { 23 | return value; 24 | } 25 | 26 | public void setValue(String value) { 27 | this.value = value; 28 | } 29 | 30 | @Override 31 | public String toString() { 32 | return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/object/SrcMappingObject.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.object; 2 | 3 | import org.apache.commons.lang.builder.ToStringBuilder; 4 | import org.apache.commons.lang.builder.ToStringStyle; 5 | 6 | /** 7 | * @author jianghang 2011-5-27 上午11:29:36 8 | */ 9 | public class SrcMappingObject { 10 | 11 | private int intValue; 12 | private Integer integerValue; 13 | private boolean start; 14 | private String name; 15 | private NestedSrcMappingObject mapping; 16 | 17 | public int getIntValue() { 18 | return intValue; 19 | } 20 | 21 | public void setIntValue(int intValue) { 22 | this.intValue = intValue; 23 | } 24 | 25 | public Integer getIntegerValue() { 26 | return integerValue; 27 | } 28 | 29 | public void setIntegerValue(Integer integerValue) { 30 | this.integerValue = integerValue; 31 | } 32 | 33 | public boolean isStart() { 34 | return start; 35 | } 36 | 37 | public void setStart(boolean start) { 38 | this.start = start; 39 | } 40 | 41 | public String getName() { 42 | return name; 43 | } 44 | 45 | public void setName(String name) { 46 | this.name = name; 47 | } 48 | 49 | public NestedSrcMappingObject getMapping() { 50 | return mapping; 51 | } 52 | 53 | public void setMapping(NestedSrcMappingObject mapping) { 54 | this.mapping = mapping; 55 | } 56 | 57 | @Override 58 | public String toString() { 59 | return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); 60 | } 61 | 62 | } 63 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/object/TargetMappingObject.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.object; 2 | 3 | import org.apache.commons.lang.builder.ToStringBuilder; 4 | import org.apache.commons.lang.builder.ToStringStyle; 5 | 6 | /** 7 | * @author jianghang 2011-5-27 上午11:29:54 8 | */ 9 | public class TargetMappingObject { 10 | 11 | private int intValue; 12 | private Integer integerValue; 13 | private boolean start; 14 | private String targetName; 15 | private NestedTargetMappingObject mapping; 16 | 17 | public int getIntValue() { 18 | return intValue; 19 | } 20 | 21 | public void setIntValue(int intValue) { 22 | this.intValue = intValue; 23 | } 24 | 25 | public Integer getIntegerValue() { 26 | return integerValue; 27 | } 28 | 29 | public void setIntegerValue(Integer integerValue) { 30 | this.integerValue = integerValue; 31 | } 32 | 33 | public boolean isStart() { 34 | return start; 35 | } 36 | 37 | public void setStart(boolean start) { 38 | this.start = start; 39 | } 40 | 41 | public String getTargetName() { 42 | return targetName; 43 | } 44 | 45 | public void setTargetName(String targetName) { 46 | this.targetName = targetName; 47 | } 48 | 49 | public NestedTargetMappingObject getMapping() { 50 | return mapping; 51 | } 52 | 53 | public void setMapping(NestedTargetMappingObject mapping) { 54 | this.mapping = mapping; 55 | } 56 | 57 | @Override 58 | public String toString() { 59 | return ToStringBuilder.reflectionToString(this, ToStringStyle.MULTI_LINE_STYLE); 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/object/inherit/FirstObject.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.object.inherit; 2 | 3 | import java.io.Serializable; 4 | 5 | /** 6 | * @author jianghang 2011-6-22 下午03:40:07 7 | */ 8 | public class FirstObject implements Serializable { 9 | 10 | private static final long serialVersionUID = 2827426602844138332L; 11 | private String firstName; 12 | private int firstValue; 13 | 14 | public FirstObject(String name){ 15 | this.firstName = name; 16 | } 17 | 18 | public String getName() { 19 | return firstName; 20 | } 21 | 22 | public void setName(String name) { 23 | this.firstName = name; 24 | } 25 | 26 | public int getFirstValue() { 27 | return firstValue; 28 | } 29 | 30 | public void setFirstValue(int firstValue) { 31 | this.firstValue = firstValue; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/object/inherit/TwoObject.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.object.inherit; 2 | 3 | import java.math.BigInteger; 4 | 5 | /** 6 | * @author jianghang 2011-6-22 下午03:40:44 7 | */ 8 | public class TwoObject extends FirstObject { 9 | 10 | private static final long serialVersionUID = 5368446589651421075L; 11 | private String twoName; 12 | private BigInteger twoValue; 13 | 14 | public TwoObject(String fristName, String twoName){ 15 | super(fristName); 16 | this.twoName = twoName; 17 | } 18 | 19 | public String getName() { 20 | return twoName; 21 | } 22 | 23 | public void setName(String name) { 24 | this.twoName = name; 25 | } 26 | 27 | public BigInteger getTwoValue() { 28 | return twoValue; 29 | } 30 | 31 | public void setTwoValue(BigInteger twoValue) { 32 | this.twoValue = twoValue; 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/performace/AbstractPerformance.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.performace; 2 | 3 | import java.lang.management.ManagementFactory; 4 | import java.lang.reflect.Method; 5 | import java.math.BigDecimal; 6 | import java.math.BigInteger; 7 | import java.text.DecimalFormat; 8 | 9 | /** 10 | * @author jianghang 2011-6-10 下午04:21:33 11 | */ 12 | public class AbstractPerformance { 13 | 14 | protected static final DecimalFormat integerFormat = new DecimalFormat("#,###"); 15 | 16 | protected static void testTemplate(TestCallback callback, CopyBean source, int count) { 17 | int warmup = 10070; 18 | // 先进行预热,加载一些类,避免影响测试 19 | for (int i = 0; i < warmup; i++) { 20 | callback.call(source); 21 | } 22 | restoreJvm(); // 进行GC回收 23 | // 进行测试 24 | long start = System.nanoTime(); 25 | for (int i = 0; i < count; i++) { 26 | callback.call(source); 27 | } 28 | long nscost = (System.nanoTime() - start); 29 | System.out.println(callback.getName() + " total cost=" + integerFormat.format(nscost) + "ns , each cost=" 30 | + nscost / count + "ns"); 31 | restoreJvm();// 进行GC回收 32 | 33 | } 34 | 35 | protected static CopyBean getBean() { 36 | CopyBean bean = new CopyBean(); 37 | bean.setIntValue(1); 38 | bean.setBoolValue(false); 39 | bean.setFloatValue(1.0f); 40 | bean.setDoubleValue(1.0d); 41 | bean.setLongValue(1l); 42 | bean.setCharValue('a'); 43 | bean.setShortValue((short) 1); 44 | bean.setByteValue((byte) 1); 45 | bean.setIntegerValue(new Integer("1")); 46 | bean.setBoolObjValue(new Boolean("false")); 47 | bean.setFloatObjValue(new Float("1.0")); 48 | bean.setDoubleObjValue(new Double("1.0")); 49 | bean.setLongObjValue(new Long("1")); 50 | bean.setCharacterValue('a'); 51 | bean.setShortObjValue(new Short("1")); 52 | bean.setByteObjValue(new Byte("1")); 53 | bean.setBigIntegerValue(new BigInteger("1")); 54 | bean.setBigDecimalValue(new BigDecimal("1")); 55 | bean.setStringValue("1"); 56 | return bean; 57 | } 58 | 59 | protected static Method getMethod(String methodName, Class... type) { 60 | try { 61 | return CopyBean.class.getMethod(methodName, type); 62 | } catch (Exception e) { 63 | e.printStackTrace(); 64 | } 65 | return null; 66 | } 67 | 68 | protected static void restoreJvm() { 69 | int maxRestoreJvmLoops = 10; 70 | long memUsedPrev = memoryUsed(); 71 | for (int i = 0; i < maxRestoreJvmLoops; i++) { 72 | System.runFinalization(); 73 | System.gc(); 74 | 75 | long memUsedNow = memoryUsed(); 76 | // break early if have no more finalization and get constant mem used 77 | if ((ManagementFactory.getMemoryMXBean().getObjectPendingFinalizationCount() == 0) 78 | && (memUsedNow >= memUsedPrev)) { 79 | break; 80 | } else { 81 | memUsedPrev = memUsedNow; 82 | } 83 | } 84 | } 85 | 86 | protected static long memoryUsed() { 87 | Runtime rt = Runtime.getRuntime(); 88 | return rt.totalMemory() - rt.freeMemory(); 89 | } 90 | 91 | } 92 | 93 | interface TestCallback { 94 | 95 | String getName(); 96 | 97 | CopyBean call(CopyBean source); 98 | } 99 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/performace/CopyBean.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.performace; 2 | 3 | import java.math.BigDecimal; 4 | import java.math.BigInteger; 5 | 6 | /** 7 | * @author jianghang 2011-6-9 下午11:23:17 8 | */ 9 | public class CopyBean { 10 | 11 | private int intValue; 12 | private boolean boolValue; 13 | private float floatValue; 14 | private double doubleValue; 15 | private long longValue; 16 | private char charValue; 17 | private byte byteValue; 18 | private short shortValue; 19 | private Integer integerValue; 20 | private Boolean boolObjValue; 21 | private Float floatObjValue; 22 | private Double doubleObjValue; 23 | private Long longObjValue; 24 | private Character characterValue; 25 | private Short shortObjValue; 26 | private Byte byteObjValue; 27 | private BigInteger bigIntegerValue; 28 | private BigDecimal bigDecimalValue; 29 | private String stringValue; 30 | 31 | public int getIntValue() { 32 | return intValue; 33 | } 34 | 35 | public void setIntValue(int intValue) { 36 | this.intValue = intValue; 37 | } 38 | 39 | public float getFloatValue() { 40 | return floatValue; 41 | } 42 | 43 | public void setFloatValue(float floatValue) { 44 | this.floatValue = floatValue; 45 | } 46 | 47 | public double getDoubleValue() { 48 | return doubleValue; 49 | } 50 | 51 | public void setDoubleValue(double doubleValue) { 52 | this.doubleValue = doubleValue; 53 | } 54 | 55 | public long getLongValue() { 56 | return longValue; 57 | } 58 | 59 | public void setLongValue(long longValue) { 60 | this.longValue = longValue; 61 | } 62 | 63 | public char getCharValue() { 64 | return charValue; 65 | } 66 | 67 | public void setCharValue(char charValue) { 68 | this.charValue = charValue; 69 | } 70 | 71 | public byte getByteValue() { 72 | return byteValue; 73 | } 74 | 75 | public void setByteValue(byte byteValue) { 76 | this.byteValue = byteValue; 77 | } 78 | 79 | public short getShortValue() { 80 | return shortValue; 81 | } 82 | 83 | public void setShortValue(short shortValue) { 84 | this.shortValue = shortValue; 85 | } 86 | 87 | public Integer getIntegerValue() { 88 | return integerValue; 89 | } 90 | 91 | public void setIntegerValue(Integer integerValue) { 92 | this.integerValue = integerValue; 93 | } 94 | 95 | public Float getFloatObjValue() { 96 | return floatObjValue; 97 | } 98 | 99 | public void setFloatObjValue(Float floatObjValue) { 100 | this.floatObjValue = floatObjValue; 101 | } 102 | 103 | public Double getDoubleObjValue() { 104 | return doubleObjValue; 105 | } 106 | 107 | public void setDoubleObjValue(Double doubleObjValue) { 108 | this.doubleObjValue = doubleObjValue; 109 | } 110 | 111 | public Long getLongObjValue() { 112 | return longObjValue; 113 | } 114 | 115 | public void setLongObjValue(Long longObjValue) { 116 | this.longObjValue = longObjValue; 117 | } 118 | 119 | public Short getShortObjValue() { 120 | return shortObjValue; 121 | } 122 | 123 | public void setShortObjValue(Short shortObjValue) { 124 | this.shortObjValue = shortObjValue; 125 | } 126 | 127 | public Byte getByteObjValue() { 128 | return byteObjValue; 129 | } 130 | 131 | public void setByteObjValue(Byte byteObjValue) { 132 | this.byteObjValue = byteObjValue; 133 | } 134 | 135 | public boolean isBoolValue() { 136 | return boolValue; 137 | } 138 | 139 | public void setBoolValue(boolean boolValue) { 140 | this.boolValue = boolValue; 141 | } 142 | 143 | public Boolean getBoolObjValue() { 144 | return boolObjValue; 145 | } 146 | 147 | public void setBoolObjValue(Boolean boolObjValue) { 148 | this.boolObjValue = boolObjValue; 149 | } 150 | 151 | public BigInteger getBigIntegerValue() { 152 | return bigIntegerValue; 153 | } 154 | 155 | public void setBigIntegerValue(BigInteger bigIntegerValue) { 156 | this.bigIntegerValue = bigIntegerValue; 157 | } 158 | 159 | public BigDecimal getBigDecimalValue() { 160 | return bigDecimalValue; 161 | } 162 | 163 | public void setBigDecimalValue(BigDecimal bigDecimalValue) { 164 | this.bigDecimalValue = bigDecimalValue; 165 | } 166 | 167 | public String getStringValue() { 168 | return stringValue; 169 | } 170 | 171 | public void setStringValue(String stringValue) { 172 | this.stringValue = stringValue; 173 | } 174 | 175 | public Character getCharacterValue() { 176 | return characterValue; 177 | } 178 | 179 | public void setCharacterValue(Character characterValue) { 180 | this.characterValue = characterValue; 181 | } 182 | 183 | } 184 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/performace/MapPerformance.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.performace; 2 | 3 | import java.util.HashMap; 4 | import java.util.Iterator; 5 | import java.util.Map; 6 | import java.util.Set; 7 | 8 | import org.apache.commons.beanutils.BeanUtils; 9 | 10 | import com.alibaba.tamper.BeanMap; 11 | 12 | /** 13 | * @author jianghang 2011-6-10 下午04:20:31 14 | */ 15 | public class MapPerformance extends AbstractPerformance { 16 | 17 | public static void main(String args[]) throws Exception { 18 | final int testCount = 1000 * 100 * 20; 19 | CopyBean bean = getBean(); 20 | // BeanMap测试 21 | final CopyBean beanMapTarget = new CopyBean(); 22 | final BeanMap beanMap = BeanMap.create(CopyBean.class); 23 | testTemplate(new TestCallback() { 24 | 25 | public String getName() { 26 | return "BeanMap"; 27 | } 28 | 29 | public CopyBean call(CopyBean source) { 30 | try { 31 | Map result = beanMap.describe(source); 32 | beanMap.populate(beanMapTarget, result); 33 | } catch (Exception e) { 34 | e.printStackTrace(); 35 | } 36 | return beanMapTarget; 37 | } 38 | 39 | }, bean, testCount); 40 | // BeanUtils测试 41 | final CopyBean beanUtilsTarget = new CopyBean(); 42 | testTemplate(new TestCallback() { 43 | 44 | public String getName() { 45 | return "BeanUtils"; 46 | } 47 | 48 | public CopyBean call(CopyBean source) { 49 | try { 50 | Map result = BeanUtils.describe(source); 51 | BeanUtils.populate(beanUtilsTarget, result); 52 | } catch (Exception e) { 53 | e.printStackTrace(); 54 | } 55 | return beanUtilsTarget; 56 | } 57 | 58 | }, bean, testCount); 59 | // Cglib测试 60 | final CopyBean cglibTarget = new CopyBean(); 61 | final net.sf.cglib.beans.BeanMap cglibBeanMap = net.sf.cglib.beans.BeanMap.create(bean); 62 | testTemplate(new TestCallback() { 63 | 64 | public String getName() { 65 | return "Cglib.BeanMap"; 66 | } 67 | 68 | public CopyBean call(CopyBean source) { 69 | try { 70 | cglibBeanMap.setBean(source); 71 | Set set = cglibBeanMap.keySet(); 72 | Map result = new HashMap(); 73 | for (Iterator iter = set.iterator(); iter.hasNext();) { 74 | Object key = iter.next(); 75 | result.put(key, cglibBeanMap.get(key)); 76 | } 77 | 78 | cglibBeanMap.setBean(cglibTarget); 79 | cglibBeanMap.putAll(result); 80 | } catch (Exception e) { 81 | e.printStackTrace(); 82 | } 83 | return beanUtilsTarget; 84 | } 85 | 86 | }, bean, testCount); 87 | 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/script/CustomFunctionClass.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.script; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import com.alibaba.tamper.process.script.lifecyle.DisposableScript; 7 | import com.alibaba.tamper.process.script.lifecyle.InitializingScript; 8 | 9 | /** 10 | * 自定义 11 | * 12 | * @author jianghang 2011-6-28 下午04:40:57 13 | */ 14 | public class CustomFunctionClass implements InitializingScript, DisposableScript { 15 | 16 | private int initial = 0; 17 | 18 | public int sum(int a, Integer b) { 19 | return a + b; 20 | } 21 | 22 | public Map newHashMap() { 23 | return new HashMap(); 24 | } 25 | 26 | public void initial() { 27 | initial += 1; 28 | } 29 | 30 | public void dispose() { 31 | initial += 1; 32 | } 33 | 34 | public int getInitial() { 35 | return initial; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/script/CustomFunctionTest.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.script; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import junit.framework.TestCase; 7 | 8 | import org.junit.Test; 9 | 10 | import com.alibaba.tamper.BeanMapping; 11 | import com.alibaba.tamper.core.builder.BeanMappingBuilder; 12 | import com.alibaba.tamper.object.SrcMappingObject; 13 | import com.alibaba.tamper.process.script.ScriptHelper; 14 | 15 | /** 16 | * @author jianghang 2011-6-28 下午05:07:51 17 | */ 18 | public class CustomFunctionTest extends TestCase { 19 | 20 | private static final String ONE_OTHER = "oneOther"; 21 | private static final String TWO_OTHER = "twoOther"; 22 | private static final String THREE_OTHER = "threeOther"; 23 | 24 | @Test 25 | public void testCustomFunction() { 26 | CustomFunctionClass function = new CustomFunctionClass(); 27 | ScriptHelper.getInstance().registerFunctionClass("customFunction", function); 28 | BeanMappingBuilder builder = new BeanMappingBuilder() { 29 | 30 | protected void configure() { 31 | behavior().debug(true).mappingEmptyStrings(false).mappingNullValue(false).trimStrings(true);// 设置行为 32 | mapping(HashMap.class, HashMap.class); 33 | fields(srcField("intValue"), targetField(ONE_OTHER, String.class)); 34 | fields(srcField("integerValue"), targetField(TWO_OTHER, String.class)); 35 | fields(srcField(null), targetField(THREE_OTHER, String.class)).script( 36 | "customFunction:sum(src.intValue,src.integerValue)"); 37 | } 38 | 39 | }; 40 | 41 | BeanMapping mapping = new BeanMapping(builder); 42 | Map src = new HashMap(); 43 | src.put("intValue", 10); 44 | src.put("integerValue", Integer.valueOf(10)); 45 | SrcMappingObject srcRef = new SrcMappingObject(); 46 | srcRef.setIntegerValue(1); 47 | 48 | Map dest = new HashMap(); 49 | mapping.mapping(src, dest); 50 | assertEquals(dest.get(ONE_OTHER), "10"); 51 | assertEquals(dest.get(TWO_OTHER), "10"); 52 | assertEquals(dest.get(THREE_OTHER), "20"); 53 | assertEquals(function.getInitial(), 2); 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/script/ScriptExecutorTest.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.script; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import junit.framework.Assert; 7 | import junit.framework.TestCase; 8 | 9 | import org.junit.Before; 10 | 11 | import com.alibaba.tamper.TestUtils; 12 | import com.alibaba.tamper.process.script.ScriptExecutor; 13 | import com.alibaba.tamper.process.script.ScriptHelper; 14 | import com.alibaba.tamper.process.script.jexl.JexlScriptExecutor; 15 | 16 | /** 17 | * @author jianghang 2011-5-24 下午04:43:01 18 | */ 19 | public class ScriptExecutorTest extends TestCase { 20 | 21 | @Before 22 | public void setUp() { 23 | try { 24 | // 清空下repository下的数据 25 | TestUtils.setField(ScriptHelper.getInstance(), "executor", null); 26 | } catch (Exception e) { 27 | Assert.fail(); 28 | } 29 | } 30 | 31 | public void testJexlScript() { 32 | ScriptExecutor executor = new JexlScriptExecutor(); 33 | doTest(executor); 34 | } 35 | 36 | public void test_system() { 37 | System.setProperty("BeanMapping.Script.Executor", "com.alibaba.tamper.process.script.jexl.JexlScriptExecutor"); 38 | doTest(ScriptHelper.getInstance().getScriptExecutor()); 39 | System.setProperty("BeanMapping.Script.Executor", ""); 40 | } 41 | 42 | public void test_service() { 43 | System.setProperty("BeanMapping.Script.Executor", ""); 44 | doTest(ScriptHelper.getInstance().getScriptExecutor()); 45 | } 46 | 47 | private void doTest(ScriptExecutor executor) { 48 | Map param = new HashMap(); 49 | // bean数据 50 | ModelA a = new ModelA(); 51 | ModelB b = new ModelB(); 52 | a.setData(b); 53 | a.setName("modelA"); 54 | b.setName("modelB"); 55 | param.put("modelA", a); 56 | 57 | // data数据 58 | Map ds = new HashMap(); 59 | ds.put("table$name", "ljh"); 60 | 61 | Map data = new HashMap(); 62 | data.put("oracle$datasource", ds); 63 | 64 | // convert数据 65 | Map converts = new HashMap(); 66 | converts.put("convert", new Convert()); 67 | 68 | param.putAll(data); 69 | param.putAll(converts); 70 | String expr = "modelA.data.name = convert.convert(oracle$datasource.table$name)"; 71 | 72 | Object obj = executor.evaluate(param, expr); 73 | assertEquals(obj, "convert"); 74 | assertEquals(a.getData().getName(), "convert"); 75 | } 76 | 77 | public static class Convert { 78 | 79 | public Object convert(Object source) { 80 | return "convert"; 81 | } 82 | } 83 | 84 | public static class ModelA { 85 | 86 | private ModelB data; 87 | 88 | private String name; 89 | 90 | public ModelB getData() { 91 | return data; 92 | } 93 | 94 | public void setData(ModelB data) { 95 | this.data = data; 96 | } 97 | 98 | public String getName() { 99 | return name; 100 | } 101 | 102 | public void setName(String name) { 103 | this.name = name; 104 | } 105 | 106 | } 107 | 108 | public static class ModelB { 109 | 110 | private String name; 111 | 112 | public String getName() { 113 | return name; 114 | } 115 | 116 | public void setName(String name) { 117 | this.name = name; 118 | } 119 | 120 | } 121 | } 122 | -------------------------------------------------------------------------------- /src/test/java/com/alibaba/tamper/script/ScriptTest.java: -------------------------------------------------------------------------------- 1 | package com.alibaba.tamper.script; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | import junit.framework.Assert; 7 | import junit.framework.TestCase; 8 | 9 | import org.junit.Before; 10 | import org.junit.Test; 11 | 12 | import com.alibaba.tamper.BeanMappingUtil; 13 | import com.alibaba.tamper.TestUtils; 14 | import com.alibaba.tamper.core.config.BeanMappingConfigHelper; 15 | import com.alibaba.tamper.core.config.BeanMappingConfigRespository; 16 | import com.alibaba.tamper.object.SrcMappingObject; 17 | 18 | /** 19 | * 测试下script配置 20 | * 21 | * @author jianghang 2011-5-31 下午09:33:57 22 | */ 23 | public class ScriptTest extends TestCase { 24 | 25 | @Before 26 | public void setUp() { 27 | try { 28 | // 清空下repository下的数据 29 | TestUtils.setField(BeanMappingConfigHelper.getInstance(), "repository", new BeanMappingConfigRespository()); 30 | BeanMappingConfigHelper.getInstance().registerConfig("mapping/script-mapping.xml"); 31 | } catch (Exception e) { 32 | Assert.fail(); 33 | } 34 | } 35 | 36 | @Test 37 | public void testScript_Ok() { 38 | // 测试下简单的script, 比如src.xxx。替代正常的srcName 39 | SrcMappingObject srcRef = new SrcMappingObject(); 40 | srcRef.setIntegerValue(1); 41 | srcRef.setIntValue(1); 42 | srcRef.setName("name"); 43 | srcRef.setStart(true); 44 | 45 | Map targetRef = new HashMap();// 测试一下mapping到一个Object对象 46 | BeanMappingUtil.mapping(srcRef, targetRef); 47 | assertEquals(2, targetRef.get("intValue")); 48 | assertEquals(1, targetRef.get("integerValue")); 49 | assertEquals(srcRef.getName(), targetRef.get("name")); 50 | assertEquals(srcRef.isStart(), targetRef.get("start")); 51 | 52 | // 反过来测试一下 53 | SrcMappingObject newSrcRef = new SrcMappingObject(); 54 | BeanMappingUtil.mapping(targetRef, newSrcRef); 55 | assertEquals(3, newSrcRef.getIntValue()); 56 | assertEquals(Integer.valueOf("1"), newSrcRef.getIntegerValue()); 57 | assertEquals(newSrcRef.getName(), targetRef.get("name")); 58 | assertEquals(newSrcRef.isStart(), targetRef.get("start")); 59 | } 60 | 61 | @Test 62 | public void testScript_value_null() { 63 | // 测试下简单的script, 比如src.xxx。替代正常的srcName 64 | SrcMappingObject srcRef = new SrcMappingObject(); 65 | srcRef.setIntegerValue(null);// 设置为null值 66 | srcRef.setIntValue(1); 67 | srcRef.setName("name"); 68 | srcRef.setStart(true); 69 | 70 | Map targetRef = new HashMap();// 测试一下mapping到一个Object对象 71 | BeanMappingUtil.mapping(srcRef, targetRef); 72 | assertEquals(2, targetRef.get("intValue")); 73 | assertEquals(1, targetRef.get("integerValue"));// 这里为默认值1 74 | assertEquals(srcRef.getName(), targetRef.get("name")); 75 | assertEquals(srcRef.isStart(), targetRef.get("start")); 76 | 77 | // 反过来测试一下 78 | SrcMappingObject newSrcRef = new SrcMappingObject(); 79 | BeanMappingUtil.mapping(targetRef, newSrcRef); 80 | assertEquals(3, newSrcRef.getIntValue()); 81 | assertEquals(Integer.valueOf(1), newSrcRef.getIntegerValue());// 这里为默认值1 82 | assertEquals(newSrcRef.getName(), targetRef.get("name")); 83 | assertEquals(newSrcRef.isStart(), targetRef.get("start")); 84 | } 85 | 86 | } 87 | -------------------------------------------------------------------------------- /src/test/resources/META-INF/services/BeanMapping.Script.Executor: -------------------------------------------------------------------------------- 1 | com.alibaba.tamper.process.script.jexl.JexlScriptExecutor -------------------------------------------------------------------------------- /src/test/resources/log4j.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /src/test/resources/mapping/config.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | -------------------------------------------------------------------------------- /src/test/resources/mapping/mapping.xml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alibaba/tamper/781c159496991705e273fb8538024dfa687235a5/src/test/resources/mapping/mapping.xml -------------------------------------------------------------------------------- /src/test/resources/mapping/script-mapping.xml: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alibaba/tamper/781c159496991705e273fb8538024dfa687235a5/src/test/resources/mapping/script-mapping.xml --------------------------------------------------------------------------------