1 16 package org.springframework.binding.mapping; 17 18 import java.io.Serializable ; 19 20 import org.apache.commons.logging.Log; 21 import org.apache.commons.logging.LogFactory; 22 import org.springframework.binding.convert.ConversionExecutor; 23 import org.springframework.binding.expression.Expression; 24 import org.springframework.binding.expression.SettableExpression; 25 import org.springframework.core.style.ToStringCreator; 26 import org.springframework.util.Assert; 27 28 35 public class Mapping implements AttributeMapper, Serializable { 36 37 protected static final Log logger = LogFactory.getLog(Mapping.class); 38 39 42 private final Expression sourceExpression; 43 44 47 private final SettableExpression targetExpression; 48 49 52 private final ConversionExecutor typeConverter; 53 54 58 private boolean required; 59 60 66 public Mapping(Expression sourceExpression, SettableExpression targetExpression, 67 ConversionExecutor typeConverter) { 68 this(sourceExpression, targetExpression, typeConverter, false); 69 } 70 71 78 protected Mapping(Expression sourceExpression, SettableExpression targetExpression, 79 ConversionExecutor typeConverter, boolean required) { 80 Assert.notNull(sourceExpression, "The source expression is required"); 81 Assert.notNull(targetExpression, "The target expression is required"); 82 this.sourceExpression = sourceExpression; 83 this.targetExpression = targetExpression; 84 this.typeConverter = typeConverter; 85 this.required = required; 86 } 87 88 95 public void map(Object source, Object target, MappingContext context) { 96 Object sourceValue = sourceExpression.evaluate(source, null); 98 if (sourceValue == null) { 99 if (required) { 100 throw new RequiredMappingException("This mapping is required; evaluation of expression '" 101 + sourceExpression + "' against source of type [" + source.getClass() 102 + "] must return a non-null value"); 103 } 104 else { 105 return; 107 } 108 } 109 Object targetValue = sourceValue; 110 if (typeConverter != null) { 111 targetValue = typeConverter.execute(sourceValue); 112 } 113 if (logger.isDebugEnabled()) { 115 logger.debug("Mapping '" + sourceExpression + "' value [" + sourceValue + "] to target property '" 116 + targetExpression + "'; setting property value to [" + targetValue + "]"); 117 } 118 targetExpression.evaluateToSet(target, targetValue, null); 119 } 120 121 public boolean equals(Object o) { 122 if (!(o instanceof Mapping)) { 123 return false; 124 } 125 Mapping other = (Mapping)o; 126 return sourceExpression.equals(other.sourceExpression) 127 && targetExpression.equals(other.targetExpression); 128 } 129 130 public int hashCode() { 131 return sourceExpression.hashCode() + targetExpression.hashCode(); 132 } 133 134 public String toString() { 135 return new ToStringCreator(this).append(sourceExpression + " -> " + targetExpression).toString(); 136 } 137 } | Popular Tags |