ma.glasnost.orika.converter.builtin.GuavaOptionalConverter Maven / Gradle / Ivy
package ma.glasnost.orika.converter.builtin;
import com.google.common.base.Optional;
import ma.glasnost.orika.Converter;
import ma.glasnost.orika.MapperFacade;
import ma.glasnost.orika.MappingContext;
import ma.glasnost.orika.metadata.Type;
import ma.glasnost.orika.metadata.TypeFactory;
/**
*
* Converter which will convert one {@linkplain Optional} field into another optional field.
*
*
* For those that wish to support the Java 8 java.util.Optional
class, the code is exactly the
* same as this class apart from the static methods to construct the Optional
classes.
*
* @param Type of the optional field to map from.
* @param Type of the optional field to map to.
*/
public class GuavaOptionalConverter implements Converter, Optional> {
private final Type sourceType;
private final Type destinationType;
private MapperFacade mapper;
/**
* Construct a new {@linkplain Optional} converter configured to convert an {@linkplain Optional} field
* to another Optional
field.
* @param sourceType Type the source {@linkplain Optional} field contains.
* @param destinationType Type the destination {@linkplain Optional} field will contain.
*/
public GuavaOptionalConverter(final Type sourceType, final Type destinationType) {
this.sourceType = sourceType;
this.destinationType = destinationType;
}
public boolean canConvert(final Type sourceType, final Type destinationType) {
final Type sourceComponentType = sourceType.getComponentType();
final Type destinationComponentType = destinationType.getComponentType();
return !(sourceComponentType == null || destinationComponentType == null)
&& this.sourceType.isAssignableFrom(sourceComponentType.getRawType())
&& this.destinationType.isAssignableFrom(destinationComponentType.getRawType());
}
public Optional convert(final Optional optionalSource, final Type> destinationType, final MappingContext mappingContext) {
if (!optionalSource.isPresent()) {
return Optional.absent();
}
final S source = optionalSource.get();
return Optional.fromNullable(mapper.map(source, sourceType, this.destinationType, mappingContext));
}
public void setMapperFacade(final MapperFacade mapper) {
this.mapper = mapper;
}
public Type> getAType() {
return getOptionalTypeOf(sourceType);
}
public Type> getBType() {
return getOptionalTypeOf(destinationType);
}
@SuppressWarnings("unchecked")
private Type> getOptionalTypeOf(Type type) {
return (Type) TypeFactory.valueOf(Optional.class, type);
}
}