1 16 package org.springframework.binding.mapping; 17 18 import org.springframework.binding.convert.ConversionExecutor; 19 import org.springframework.binding.convert.ConversionService; 20 import org.springframework.binding.convert.support.DefaultConversionService; 21 import org.springframework.binding.expression.Expression; 22 import org.springframework.binding.expression.ExpressionParser; 23 import org.springframework.binding.expression.SettableExpression; 24 import org.springframework.util.Assert; 25 26 41 public class MappingBuilder { 42 43 46 private Expression sourceExpression; 47 48 51 private SettableExpression targetExpression; 52 53 56 private Class sourceType; 57 58 61 private Class targetType; 62 63 66 private ExpressionParser expressionParser; 67 68 71 private ConversionService conversionService = new DefaultConversionService(); 72 73 76 private boolean required; 77 78 83 public MappingBuilder(ExpressionParser expressionParser) { 84 Assert.notNull(expressionParser, "The expression parser is required"); 85 this.expressionParser = expressionParser; 86 } 87 88 94 public void setConversionService(ConversionService conversionService) { 95 this.conversionService = conversionService; 96 } 97 98 103 public MappingBuilder source(String expressionString) { 104 sourceExpression = expressionParser.parseExpression(expressionString); 105 return this; 106 } 107 108 113 public MappingBuilder target(String expressionString) { 114 targetExpression = (SettableExpression)expressionParser.parseExpression(expressionString); 115 return this; 116 } 117 118 125 public MappingBuilder from(Class sourceType) { 126 this.sourceType = sourceType; 127 return this; 128 } 129 130 135 public MappingBuilder to(Class targetType) { 136 this.targetType = targetType; 137 return this; 138 } 139 140 144 public MappingBuilder required() { 145 this.required = true; 146 return this; 147 } 148 149 155 public Mapping value() { 156 Assert.notNull(sourceExpression, "The source expression must be set at a minimum"); 157 if (targetExpression == null) { 158 targetExpression = (SettableExpression)sourceExpression; 159 } 160 ConversionExecutor typeConverter = null; 161 if (sourceType != null) { 162 Assert.notNull(targetType, "The target type is required when the source type is specified"); 163 typeConverter = conversionService.getConversionExecutor(sourceType, targetType); 164 } 165 Mapping result; 166 if (required) { 167 result = new RequiredMapping(sourceExpression, targetExpression, typeConverter); 168 } else { 169 result = new Mapping(sourceExpression, targetExpression, typeConverter); 170 } 171 sourceExpression = null; 172 targetExpression = null; 173 sourceType = null; 174 targetType = null; 175 required = false; 176 return result; 177 } 178 } | Popular Tags |