#12 Using spaces instead of tabs for indentation

This commit is contained in:
Gunnar Morling 2013-04-07 13:11:53 +02:00
parent be84f96b84
commit cff12a5b49
46 changed files with 1803 additions and 1796 deletions

View File

@ -16,7 +16,8 @@
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

View File

@ -29,5 +29,5 @@ import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.SOURCE)
public @interface Mapper {
Class<?>[] uses() default { };
Class<?>[] uses() default { };
}

View File

@ -18,28 +18,28 @@ package org.mapstruct;
public class Mappers {
private final static String IMPLEMENTATION_SUFFIX = "Impl";
private final static String IMPLEMENTATION_SUFFIX = "Impl";
/**
* TODO: Check that
* - clazz is an interface
* - the implementation type implements clazz
* - clazz is annotated with @Mapper
*
* TODO: Use privileged action
*/
@SuppressWarnings("unchecked")
public static <T> T getMapper(Class<T> clazz) {
try {
/**
* TODO: Check that
* - clazz is an interface
* - the implementation type implements clazz
* - clazz is annotated with @Mapper
*
* TODO: Use privileged action
*/
@SuppressWarnings("unchecked")
public static <T> T getMapper(Class<T> clazz) {
try {
// ClassLoader classLoader = clazz.getClassLoader();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
return (T) classLoader.loadClass( clazz.getName() + IMPLEMENTATION_SUFFIX ).newInstance();
}
catch ( Exception e ) {
e.printStackTrace();
throw new RuntimeException( e );
}
}
return (T) classLoader.loadClass( clazz.getName() + IMPLEMENTATION_SUFFIX ).newInstance();
}
catch ( Exception e ) {
e.printStackTrace();
throw new RuntimeException( e );
}
}
}

View File

@ -17,7 +17,7 @@ package org.mapstruct;
public @interface Mapping {
String source();
String source();
String target();
String target();
}

View File

@ -18,5 +18,5 @@ package org.mapstruct;
public @interface Mappings {
Mapping[] value();
Mapping[] value();
}

View File

@ -23,10 +23,10 @@ import static org.fest.assertions.Assertions.assertThat;
public class MappersTest {
@Test
public void shouldReturnImplementationInstance() {
@Test
public void shouldReturnImplementationInstance() {
Foo mapper = Mappers.getMapper( Foo.class );
assertThat( mapper ).isNotNull();
}
Foo mapper = Mappers.getMapper( Foo.class );
assertThat( mapper ).isNotNull();
}
}

View File

@ -16,8 +16,9 @@
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>

View File

@ -17,49 +17,49 @@ package org.mapstruct.itest;
public class Source {
private int foo;
private Long bar;
private int qax;
private Long baz;
private int zip;
private int foo;
private Long bar;
private int qax;
private Long baz;
private int zip;
public int getFoo() {
return foo;
}
public int getFoo() {
return foo;
}
public void setFoo(int foo) {
this.foo = foo;
}
public void setFoo(int foo) {
this.foo = foo;
}
public Long getBar() {
return bar;
}
public Long getBar() {
return bar;
}
public void setBar(Long bar) {
this.bar = bar;
}
public void setBar(Long bar) {
this.bar = bar;
}
public int getQax() {
return qax;
}
public int getQax() {
return qax;
}
public void setQax(int qax) {
this.qax = qax;
}
public void setQax(int qax) {
this.qax = qax;
}
public Long getBaz() {
return baz;
}
public Long getBaz() {
return baz;
}
public void setBaz(Long baz) {
this.baz = baz;
}
public void setBaz(Long baz) {
this.baz = baz;
}
public int getZip() {
return zip;
}
public int getZip() {
return zip;
}
public void setZip(int zip) {
this.zip = zip;
}
public void setZip(int zip) {
this.zip = zip;
}
}

View File

@ -23,13 +23,13 @@ import org.mapstruct.Mappings;
@Mapper
public interface SourceTargetMapper {
public static SourceTargetMapper INSTANCE = Mappers.getMapper( SourceTargetMapper.class );
public static SourceTargetMapper INSTANCE = Mappers.getMapper( SourceTargetMapper.class );
@Mappings({
@Mapping(source = "qax", target = "baz"),
@Mapping(source = "baz", target = "qax")
})
Target sourceToTarget(Source source);
@Mappings({
@Mapping(source = "qax", target = "baz"),
@Mapping(source = "baz", target = "qax")
})
Target sourceToTarget(Source source);
Source targetToSource(Target target);
Source targetToSource(Target target);
}

View File

@ -17,49 +17,49 @@ package org.mapstruct.itest;
public class Target {
private Long foo;
private int bar;
private Long baz;
private int qax;
private String zip;
private Long foo;
private int bar;
private Long baz;
private int qax;
private String zip;
public Long getFoo() {
return foo;
}
public Long getFoo() {
return foo;
}
public void setFoo(Long foo) {
this.foo = foo;
}
public void setFoo(Long foo) {
this.foo = foo;
}
public int getBar() {
return bar;
}
public int getBar() {
return bar;
}
public void setBar(int bar) {
this.bar = bar;
}
public void setBar(int bar) {
this.bar = bar;
}
public Long getBaz() {
return baz;
}
public Long getBaz() {
return baz;
}
public void setBaz(Long baz) {
this.baz = baz;
}
public void setBaz(Long baz) {
this.baz = baz;
}
public int getQax() {
return qax;
}
public int getQax() {
return qax;
}
public void setQax(int qax) {
this.qax = qax;
}
public void setQax(int qax) {
this.qax = qax;
}
public String getZip() {
return zip;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public void setZip(String zip) {
this.zip = zip;
}
}

View File

@ -21,70 +21,70 @@ import static org.fest.assertions.Assertions.assertThat;
public class ConversionTest {
@Test
public void shouldApplyConversions() {
Source source = new Source();
source.setFoo( 42 );
source.setBar( 23L );
source.setZip( 73 );
@Test
public void shouldApplyConversions() {
Source source = new Source();
source.setFoo( 42 );
source.setBar( 23L );
source.setZip( 73 );
Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source );
Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source );
assertThat( target ).isNotNull();
assertThat( target.getFoo() ).isEqualTo( Long.valueOf( 42 ) );
assertThat( target.getBar() ).isEqualTo( 23 );
assertThat( target.getZip() ).isEqualTo( "73" );
}
assertThat( target ).isNotNull();
assertThat( target.getFoo() ).isEqualTo( Long.valueOf( 42 ) );
assertThat( target.getBar() ).isEqualTo( 23 );
assertThat( target.getZip() ).isEqualTo( "73" );
}
@Test
public void shouldHandleNulls() {
Source source = new Source();
Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source );
@Test
public void shouldHandleNulls() {
Source source = new Source();
Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source );
assertThat( target ).isNotNull();
assertThat( target.getFoo() ).isEqualTo( Long.valueOf( 0 ) );
assertThat( target.getBar() ).isEqualTo( 0 );
assertThat( target.getZip() ).isEqualTo( "0" );
}
assertThat( target ).isNotNull();
assertThat( target.getFoo() ).isEqualTo( Long.valueOf( 0 ) );
assertThat( target.getBar() ).isEqualTo( 0 );
assertThat( target.getZip() ).isEqualTo( "0" );
}
@Test
public void shouldApplyConversionsToMappedProperties() {
Source source = new Source();
source.setQax( 42 );
source.setBaz( 23L );
@Test
public void shouldApplyConversionsToMappedProperties() {
Source source = new Source();
source.setQax( 42 );
source.setBaz( 23L );
Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source );
Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source );
assertThat( target ).isNotNull();
assertThat( target.getBaz() ).isEqualTo( Long.valueOf( 42 ) );
assertThat( target.getQax() ).isEqualTo( 23 );
}
assertThat( target ).isNotNull();
assertThat( target.getBaz() ).isEqualTo( Long.valueOf( 42 ) );
assertThat( target.getQax() ).isEqualTo( 23 );
}
@Test
public void shouldApplyConversionsForReverseMapping() {
Target target = new Target();
target.setFoo( 42L );
target.setBar( 23 );
target.setZip( "73" );
@Test
public void shouldApplyConversionsForReverseMapping() {
Target target = new Target();
target.setFoo( 42L );
target.setBar( 23 );
target.setZip( "73" );
Source source = SourceTargetMapper.INSTANCE.targetToSource( target );
Source source = SourceTargetMapper.INSTANCE.targetToSource( target );
assertThat( source ).isNotNull();
assertThat( source.getFoo() ).isEqualTo( 42 );
assertThat( source.getBar() ).isEqualTo( 23 );
assertThat( source.getZip() ).isEqualTo( 73 );
}
assertThat( source ).isNotNull();
assertThat( source.getFoo() ).isEqualTo( 42 );
assertThat( source.getBar() ).isEqualTo( 23 );
assertThat( source.getZip() ).isEqualTo( 73 );
}
@Test
public void shouldApplyConversionsToMappedPropertiesForReverseMapping() {
Target target = new Target();
target.setQax( 42 );
target.setBaz( 23L );
@Test
public void shouldApplyConversionsToMappedPropertiesForReverseMapping() {
Target target = new Target();
target.setQax( 42 );
target.setBaz( 23L );
Source source = SourceTargetMapper.INSTANCE.targetToSource( target );
Source source = SourceTargetMapper.INSTANCE.targetToSource( target );
assertThat( source ).isNotNull();
assertThat( source.getBaz() ).isEqualTo( 42 );
assertThat( source.getQax() ).isEqualTo( 23 );
}
assertThat( source ).isNotNull();
assertThat( source.getBaz() ).isEqualTo( 42 );
assertThat( source.getQax() ).isEqualTo( 23 );
}
}

View File

@ -16,7 +16,8 @@
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

View File

@ -16,7 +16,8 @@
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

View File

@ -16,116 +16,119 @@
limitations under the License.
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-parent</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../parent/pom.xml</relativePath>
</parent>
<parent>
<groupId>org.mapstruct</groupId>
<artifactId>mapstruct-parent</artifactId>
<version>1.0-SNAPSHOT</version>
<relativePath>../parent/pom.xml</relativePath>
</parent>
<artifactId>mapstruct-processor</artifactId>
<packaging>jar</packaging>
<name>MapStruct Processor</name>
<artifactId>mapstruct-processor</artifactId>
<packaging>jar</packaging>
<name>MapStruct Processor</name>
<properties>
<prism.directory>${project.build.directory}/generated-sources/prims</prism.directory>
</properties>
<properties>
<prism.directory>${project.build.directory}/generated-sources/prims</prism.directory>
</properties>
<dependencies>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<dependency>
<groupId>com.jolira</groupId>
<artifactId>hickory</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>mapstruct</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<dependencies>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
</dependency>
<dependency>
<groupId>com.jolira</groupId>
<artifactId>hickory</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>${project.groupId}</groupId>
<artifactId>mapstruct</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.testng</groupId>
<artifactId>testng</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.easytesting</groupId>
<artifactId>fest-assert</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy</id>
<phase>generate-test-resources</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/test-dependencies</outputDirectory>
<stripVersion>true</stripVersion>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<configuration>
<defaultOutputDirectory>${prism.directory}</defaultOutputDirectory>
<processors>
<processor>net.java.dev.hickory.prism.internal.PrismGenerator</processor>
</processors>
</configuration>
<executions>
<execution>
<id>process</id>
<phase>generate-sources</phase>
<goals>
<goal>process</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.jolira</groupId>
<artifactId>hickory</artifactId>
<version>${com.jolira.hickory.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>${prism.directory}</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<executions>
<execution>
<id>copy</id>
<phase>generate-test-resources</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/test-dependencies
</outputDirectory>
<stripVersion>true</stripVersion>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.bsc.maven</groupId>
<artifactId>maven-processor-plugin</artifactId>
<configuration>
<defaultOutputDirectory>${prism.directory}</defaultOutputDirectory>
<processors>
<processor>net.java.dev.hickory.prism.internal.PrismGenerator
</processor>
</processors>
</configuration>
<executions>
<execution>
<id>process</id>
<phase>generate-sources</phase>
<goals>
<goal>process</goal>
</goals>
</execution>
</executions>
<dependencies>
<dependency>
<groupId>com.jolira</groupId>
<artifactId>hickory</artifactId>
<version>${com.jolira.hickory.version}</version>
</dependency>
</dependencies>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<executions>
<execution>
<id>add-source</id>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>${prism.directory}</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>

View File

@ -55,360 +55,360 @@ import static javax.lang.model.util.ElementFilter.methodsIn;
public class MapperGenerationVisitor extends ElementKindVisitor6<Void, Void> {
private final static String IMPLEMENTATION_SUFFIX = "Impl";
private final ProcessingEnvironment processingEnvironment;
private final Types typeUtils;
private final Elements elementUtils;
private final TypeUtil typeUtil;
public MapperGenerationVisitor(ProcessingEnvironment processingEnvironment) {
this.processingEnvironment = processingEnvironment;
this.typeUtils = processingEnvironment.getTypeUtils();
this.elementUtils = processingEnvironment.getElementUtils();
this.typeUtil = new TypeUtil( elementUtils, typeUtils );
}
@Override
public Void visitTypeAsInterface(TypeElement element, Void p) {
Mapper model = retrieveModel( element );
String sourceFileName = element.getQualifiedName() + IMPLEMENTATION_SUFFIX;
writeModelToSourceFile( sourceFileName, model );
return null;
}
private void writeModelToSourceFile(String fileName, Mapper model) {
JavaFileObject sourceFile;
try {
sourceFile = processingEnvironment.getFiler().createSourceFile( fileName );
}
catch ( IOException e ) {
throw new RuntimeException( e );
}
ModelWriter modelWriter = new ModelWriter( "mapper-implementation.ftl" );
modelWriter.writeModel( sourceFile, model );
}
private Mapper retrieveModel(TypeElement element) {
List<Method> methods = retrieveMethods( null, element );
List<BeanMapping> mappings = getMappings( methods );
List<Type> usedMapperTypes = getUsedMapperTypes( element );
Mapper mapper = new Mapper(
elementUtils.getPackageOf( element ).getQualifiedName().toString(),
element.getSimpleName().toString(),
element.getSimpleName() + IMPLEMENTATION_SUFFIX,
mappings,
usedMapperTypes
);
return mapper;
}
private List<BeanMapping> getMappings(List<Method> methods) {
Conversions conversions = new Conversions( elementUtils, typeUtils, typeUtil );
List<BeanMapping> mappings = new ArrayList<BeanMapping>();
Set<Method> processedMethods = new HashSet<Method>();
for ( Method method : methods ) {
if ( processedMethods.contains( method ) ) {
continue;
}
MappingMethod mappingMethod = new MappingMethod(
method.getDeclaringMapper(),
method.getName(),
method.getParameterName(),
getElementMappingMethod( methods, method )
);
MappingMethod reverseMappingMethod = null;
Method rawReverseMappingMethod = getReverseMappingMethod( methods, method );
if ( rawReverseMappingMethod != null ) {
processedMethods.add( rawReverseMappingMethod );
reverseMappingMethod = new MappingMethod(
rawReverseMappingMethod.getDeclaringMapper(),
rawReverseMappingMethod.getName(),
rawReverseMappingMethod.getParameterName(),
getElementMappingMethod( methods, rawReverseMappingMethod )
);
}
List<PropertyMapping> propertyMappings = new ArrayList<PropertyMapping>();
for ( MappedProperty property : method.getMappedProperties() ) {
Method propertyMappingMethod = getPropertyMappingMethod( methods, property );
Method reversePropertyMappingMethod = getReversePropertyMappingMethod( methods, property );
Conversion conversion = conversions.getConversion( property.getSourceType(), property.getTargetType() );
propertyMappings.add(
new PropertyMapping(
property.getSourceName(),
property.getSourceType(),
property.getTargetName(),
property.getTargetType(),
propertyMappingMethod != null ? new MappingMethod(
propertyMappingMethod.getDeclaringMapper(),
propertyMappingMethod.getName(),
propertyMappingMethod.getParameterName()
) : null,
reversePropertyMappingMethod != null ? new MappingMethod(
reversePropertyMappingMethod.getDeclaringMapper(),
reversePropertyMappingMethod.getName(),
reversePropertyMappingMethod.getParameterName()
) : null,
conversion != null ? conversion.to(
mappingMethod.getParameterName() + "." + getAccessor(
property.getSourceName()
),
property.getTargetType()
) : null,
conversion != null ? conversion.from(
reverseMappingMethod.getParameterName() + "." + getAccessor(
property.getTargetName()
),
property.getSourceType()
) : null
)
);
}
BeanMapping mapping = new BeanMapping(
method.getSourceType(),
method.getTargetType(),
propertyMappings,
mappingMethod,
reverseMappingMethod
);
mappings.add( mapping );
}
return mappings;
}
private List<Type> getUsedMapperTypes(TypeElement element) {
List<Type> usedMapperTypes = new LinkedList<Type>();
MapperPrism mapperPrism = MapperPrism.getInstanceOn( element );
for ( TypeMirror usedMapper : mapperPrism.uses() ) {
usedMapperTypes.add( typeUtil.retrieveType( usedMapper ) );
}
return usedMapperTypes;
}
private String getAccessor(String name) {
return "get" + capitalize( name ) + "()";
}
private String capitalize(String name) {
return name.substring( 0, 1 ).toUpperCase() + name.substring( 1 );
}
private MappingMethod getElementMappingMethod(Iterable<Method> methods, Method method) {
Method elementMappingMethod = null;
for ( Method oneMethod : methods ) {
if ( oneMethod.getSourceType().equals( method.getSourceType().getElementType() ) ) {
elementMappingMethod = oneMethod;
break;
}
}
return elementMappingMethod == null ? null : new MappingMethod(
elementMappingMethod.getDeclaringMapper(),
elementMappingMethod.getName(),
elementMappingMethod.getParameterName()
);
}
private Method getPropertyMappingMethod(Iterable<Method> rawMethods, MappedProperty property) {
for ( Method oneMethod : rawMethods ) {
if ( oneMethod.getSourceType().equals( property.getSourceType() ) && oneMethod.getTargetType()
.equals( property.getTargetType() ) ) {
return oneMethod;
}
}
return null;
}
private Method getReversePropertyMappingMethod(Iterable<Method> methods, MappedProperty property) {
for ( Method method : methods ) {
if ( method.getSourceType().equals( property.getTargetType() ) && method.getTargetType()
.equals( property.getSourceType() ) ) {
return method;
}
}
return null;
}
private Method getReverseMappingMethod(List<Method> rawMethods,
Method method) {
for ( Method oneMethod : rawMethods ) {
if ( oneMethod.reverses( method ) ) {
return oneMethod;
}
}
return null;
}
private List<Method> retrieveMethods(Type declaringMapper, Element element) {
List<Method> methods = new ArrayList<Method>();
for ( ExecutableElement method : methodsIn( element.getEnclosedElements() ) ) {
Parameter parameter = retrieveParameter( method );
Type returnType = retrieveReturnType( method );
List<MappedProperty> properties = retrieveMappedProperties( method );
methods.add(
new Method(
declaringMapper,
method.getSimpleName().toString(),
parameter.getName(),
parameter.getType(),
returnType,
properties
)
);
}
List<Type> usedMapperTypes = new LinkedList<Type>();
MapperPrism mapperPrism = MapperPrism.getInstanceOn( element );
if ( mapperPrism != null ) {
for ( TypeMirror usedMapper : mapperPrism.uses() ) {
methods.addAll(
retrieveMethods(
typeUtil.retrieveType( usedMapper ),
( (DeclaredType) usedMapper ).asElement()
)
);
}
}
return methods;
}
private List<MappedProperty> retrieveMappedProperties(ExecutableElement method) {
Map<String, Mapping> mappings = new HashMap<String, Mapping>();
MappingPrism mappingAnnotation = MappingPrism.getInstanceOn( method );
MappingsPrism mappingsAnnotation = MappingsPrism.getInstanceOn( method );
if ( mappingAnnotation != null ) {
mappings.put( mappingAnnotation.source(), getMapping( mappingAnnotation ) );
}
if ( mappingsAnnotation != null ) {
mappings.putAll( getMappings( mappingsAnnotation ) );
}
return getMappedProperties( method, mappings );
}
private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) {
Element returnTypeElement = typeUtils.asElement( method.getReturnType() );
Element parameterElement = typeUtils.asElement( method.getParameters().get( 0 ).asType() );
List<MappedProperty> properties = new ArrayList<MappedProperty>();
for ( ExecutableElement getterMethod : getterMethodsIn( parameterElement.getEnclosedElements() ) ) {
String sourcePropertyName = getPropertyName( getterMethod );
Mapping mapping = mappings.get( sourcePropertyName );
for ( ExecutableElement setterMethod : setterMethodsIn( returnTypeElement.getEnclosedElements() ) ) {
String targetPropertyName = getPropertyName( setterMethod );
if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) {
properties.add(
new MappedProperty(
sourcePropertyName,
retrieveReturnType( getterMethod ),
mapping != null ? mapping.getTargetName() : targetPropertyName,
retrieveParameter( setterMethod ).getType()
)
);
}
}
}
return properties;
}
private String getPropertyName(ExecutableElement getterOrSetterMethod) {
//TODO consider is/has
return Introspector.decapitalize(
getterOrSetterMethod.getSimpleName().toString().substring( 3 )
);
}
private Map<String, Mapping> getMappings(MappingsPrism mappingsAnnotation) {
Map<String, Mapping> mappings = new HashMap<String, Mapping>();
for ( MappingPrism mapping : mappingsAnnotation.value() ) {
mappings.put( mapping.source(), getMapping( mapping ) );
}
return mappings;
}
private Mapping getMapping(MappingPrism mapping) {
return new Mapping( mapping.source(), mapping.target() );
}
private Parameter retrieveParameter(ExecutableElement method) {
List<? extends VariableElement> parameters = method.getParameters();
if ( parameters.size() != 1 ) {
//TODO: Log error
return null;
}
VariableElement parameter = parameters.get( 0 );
private final static String IMPLEMENTATION_SUFFIX = "Impl";
private final ProcessingEnvironment processingEnvironment;
private final Types typeUtils;
private final Elements elementUtils;
private final TypeUtil typeUtil;
public MapperGenerationVisitor(ProcessingEnvironment processingEnvironment) {
this.processingEnvironment = processingEnvironment;
this.typeUtils = processingEnvironment.getTypeUtils();
this.elementUtils = processingEnvironment.getElementUtils();
this.typeUtil = new TypeUtil( elementUtils, typeUtils );
}
@Override
public Void visitTypeAsInterface(TypeElement element, Void p) {
Mapper model = retrieveModel( element );
String sourceFileName = element.getQualifiedName() + IMPLEMENTATION_SUFFIX;
writeModelToSourceFile( sourceFileName, model );
return null;
}
private void writeModelToSourceFile(String fileName, Mapper model) {
JavaFileObject sourceFile;
try {
sourceFile = processingEnvironment.getFiler().createSourceFile( fileName );
}
catch ( IOException e ) {
throw new RuntimeException( e );
}
ModelWriter modelWriter = new ModelWriter( "mapper-implementation.ftl" );
modelWriter.writeModel( sourceFile, model );
}
private Mapper retrieveModel(TypeElement element) {
List<Method> methods = retrieveMethods( null, element );
List<BeanMapping> mappings = getMappings( methods );
List<Type> usedMapperTypes = getUsedMapperTypes( element );
Mapper mapper = new Mapper(
elementUtils.getPackageOf( element ).getQualifiedName().toString(),
element.getSimpleName().toString(),
element.getSimpleName() + IMPLEMENTATION_SUFFIX,
mappings,
usedMapperTypes
);
return mapper;
}
private List<BeanMapping> getMappings(List<Method> methods) {
Conversions conversions = new Conversions( elementUtils, typeUtils, typeUtil );
List<BeanMapping> mappings = new ArrayList<BeanMapping>();
Set<Method> processedMethods = new HashSet<Method>();
for ( Method method : methods ) {
if ( processedMethods.contains( method ) ) {
continue;
}
MappingMethod mappingMethod = new MappingMethod(
method.getDeclaringMapper(),
method.getName(),
method.getParameterName(),
getElementMappingMethod( methods, method )
);
MappingMethod reverseMappingMethod = null;
Method rawReverseMappingMethod = getReverseMappingMethod( methods, method );
if ( rawReverseMappingMethod != null ) {
processedMethods.add( rawReverseMappingMethod );
reverseMappingMethod = new MappingMethod(
rawReverseMappingMethod.getDeclaringMapper(),
rawReverseMappingMethod.getName(),
rawReverseMappingMethod.getParameterName(),
getElementMappingMethod( methods, rawReverseMappingMethod )
);
}
List<PropertyMapping> propertyMappings = new ArrayList<PropertyMapping>();
for ( MappedProperty property : method.getMappedProperties() ) {
Method propertyMappingMethod = getPropertyMappingMethod( methods, property );
Method reversePropertyMappingMethod = getReversePropertyMappingMethod( methods, property );
Conversion conversion = conversions.getConversion( property.getSourceType(), property.getTargetType() );
propertyMappings.add(
new PropertyMapping(
property.getSourceName(),
property.getSourceType(),
property.getTargetName(),
property.getTargetType(),
propertyMappingMethod != null ? new MappingMethod(
propertyMappingMethod.getDeclaringMapper(),
propertyMappingMethod.getName(),
propertyMappingMethod.getParameterName()
) : null,
reversePropertyMappingMethod != null ? new MappingMethod(
reversePropertyMappingMethod.getDeclaringMapper(),
reversePropertyMappingMethod.getName(),
reversePropertyMappingMethod.getParameterName()
) : null,
conversion != null ? conversion.to(
mappingMethod.getParameterName() + "." + getAccessor(
property.getSourceName()
),
property.getTargetType()
) : null,
conversion != null ? conversion.from(
reverseMappingMethod.getParameterName() + "." + getAccessor(
property.getTargetName()
),
property.getSourceType()
) : null
)
);
}
BeanMapping mapping = new BeanMapping(
method.getSourceType(),
method.getTargetType(),
propertyMappings,
mappingMethod,
reverseMappingMethod
);
mappings.add( mapping );
}
return mappings;
}
private List<Type> getUsedMapperTypes(TypeElement element) {
List<Type> usedMapperTypes = new LinkedList<Type>();
MapperPrism mapperPrism = MapperPrism.getInstanceOn( element );
for ( TypeMirror usedMapper : mapperPrism.uses() ) {
usedMapperTypes.add( typeUtil.retrieveType( usedMapper ) );
}
return usedMapperTypes;
}
private String getAccessor(String name) {
return "get" + capitalize( name ) + "()";
}
private String capitalize(String name) {
return name.substring( 0, 1 ).toUpperCase() + name.substring( 1 );
}
private MappingMethod getElementMappingMethod(Iterable<Method> methods, Method method) {
Method elementMappingMethod = null;
for ( Method oneMethod : methods ) {
if ( oneMethod.getSourceType().equals( method.getSourceType().getElementType() ) ) {
elementMappingMethod = oneMethod;
break;
}
}
return elementMappingMethod == null ? null : new MappingMethod(
elementMappingMethod.getDeclaringMapper(),
elementMappingMethod.getName(),
elementMappingMethod.getParameterName()
);
}
private Method getPropertyMappingMethod(Iterable<Method> rawMethods, MappedProperty property) {
for ( Method oneMethod : rawMethods ) {
if ( oneMethod.getSourceType().equals( property.getSourceType() ) && oneMethod.getTargetType()
.equals( property.getTargetType() ) ) {
return oneMethod;
}
}
return null;
}
private Method getReversePropertyMappingMethod(Iterable<Method> methods, MappedProperty property) {
for ( Method method : methods ) {
if ( method.getSourceType().equals( property.getTargetType() ) && method.getTargetType()
.equals( property.getSourceType() ) ) {
return method;
}
}
return null;
}
private Method getReverseMappingMethod(List<Method> rawMethods,
Method method) {
for ( Method oneMethod : rawMethods ) {
if ( oneMethod.reverses( method ) ) {
return oneMethod;
}
}
return null;
}
private List<Method> retrieveMethods(Type declaringMapper, Element element) {
List<Method> methods = new ArrayList<Method>();
for ( ExecutableElement method : methodsIn( element.getEnclosedElements() ) ) {
Parameter parameter = retrieveParameter( method );
Type returnType = retrieveReturnType( method );
List<MappedProperty> properties = retrieveMappedProperties( method );
methods.add(
new Method(
declaringMapper,
method.getSimpleName().toString(),
parameter.getName(),
parameter.getType(),
returnType,
properties
)
);
}
List<Type> usedMapperTypes = new LinkedList<Type>();
MapperPrism mapperPrism = MapperPrism.getInstanceOn( element );
if ( mapperPrism != null ) {
for ( TypeMirror usedMapper : mapperPrism.uses() ) {
methods.addAll(
retrieveMethods(
typeUtil.retrieveType( usedMapper ),
( (DeclaredType) usedMapper ).asElement()
)
);
}
}
return methods;
}
private List<MappedProperty> retrieveMappedProperties(ExecutableElement method) {
Map<String, Mapping> mappings = new HashMap<String, Mapping>();
MappingPrism mappingAnnotation = MappingPrism.getInstanceOn( method );
MappingsPrism mappingsAnnotation = MappingsPrism.getInstanceOn( method );
if ( mappingAnnotation != null ) {
mappings.put( mappingAnnotation.source(), getMapping( mappingAnnotation ) );
}
if ( mappingsAnnotation != null ) {
mappings.putAll( getMappings( mappingsAnnotation ) );
}
return getMappedProperties( method, mappings );
}
private List<MappedProperty> getMappedProperties(ExecutableElement method, Map<String, Mapping> mappings) {
Element returnTypeElement = typeUtils.asElement( method.getReturnType() );
Element parameterElement = typeUtils.asElement( method.getParameters().get( 0 ).asType() );
List<MappedProperty> properties = new ArrayList<MappedProperty>();
for ( ExecutableElement getterMethod : getterMethodsIn( parameterElement.getEnclosedElements() ) ) {
String sourcePropertyName = getPropertyName( getterMethod );
Mapping mapping = mappings.get( sourcePropertyName );
for ( ExecutableElement setterMethod : setterMethodsIn( returnTypeElement.getEnclosedElements() ) ) {
String targetPropertyName = getPropertyName( setterMethod );
if ( targetPropertyName.equals( mapping != null ? mapping.getTargetName() : sourcePropertyName ) ) {
properties.add(
new MappedProperty(
sourcePropertyName,
retrieveReturnType( getterMethod ),
mapping != null ? mapping.getTargetName() : targetPropertyName,
retrieveParameter( setterMethod ).getType()
)
);
}
}
}
return properties;
}
private String getPropertyName(ExecutableElement getterOrSetterMethod) {
//TODO consider is/has
return Introspector.decapitalize(
getterOrSetterMethod.getSimpleName().toString().substring( 3 )
);
}
private Map<String, Mapping> getMappings(MappingsPrism mappingsAnnotation) {
Map<String, Mapping> mappings = new HashMap<String, Mapping>();
for ( MappingPrism mapping : mappingsAnnotation.value() ) {
mappings.put( mapping.source(), getMapping( mapping ) );
}
return mappings;
}
private Mapping getMapping(MappingPrism mapping) {
return new Mapping( mapping.source(), mapping.target() );
}
private Parameter retrieveParameter(ExecutableElement method) {
List<? extends VariableElement> parameters = method.getParameters();
if ( parameters.size() != 1 ) {
//TODO: Log error
return null;
}
VariableElement parameter = parameters.get( 0 );
return new Parameter(
parameter.getSimpleName().toString(),
typeUtil.retrieveType( parameter.asType() )
);
}
return new Parameter(
parameter.getSimpleName().toString(),
typeUtil.retrieveType( parameter.asType() )
);
}
private Type retrieveReturnType(ExecutableElement method) {
return typeUtil.retrieveType( method.getReturnType() );
}
private Type retrieveReturnType(ExecutableElement method) {
return typeUtil.retrieveType( method.getReturnType() );
}
private List<ExecutableElement> getterMethodsIn(Iterable<? extends Element> elements) {
List<ExecutableElement> getterMethods = new LinkedList<ExecutableElement>();
private List<ExecutableElement> getterMethodsIn(Iterable<? extends Element> elements) {
List<ExecutableElement> getterMethods = new LinkedList<ExecutableElement>();
for ( ExecutableElement method : methodsIn( elements ) ) {
//TODO: consider is/has
String name = method.getSimpleName().toString();
for ( ExecutableElement method : methodsIn( elements ) ) {
//TODO: consider is/has
String name = method.getSimpleName().toString();
if ( name.startsWith( "get" ) && name.length() > 3 && method.getParameters()
.isEmpty() && method.getReturnType().getKind() != TypeKind.VOID ) {
getterMethods.add( method );
}
}
if ( name.startsWith( "get" ) && name.length() > 3 && method.getParameters()
.isEmpty() && method.getReturnType().getKind() != TypeKind.VOID ) {
getterMethods.add( method );
}
}
return getterMethods;
}
return getterMethods;
}
private List<ExecutableElement> setterMethodsIn(Iterable<? extends Element> elements) {
List<ExecutableElement> setterMethods = new LinkedList<ExecutableElement>();
private List<ExecutableElement> setterMethodsIn(Iterable<? extends Element> elements) {
List<ExecutableElement> setterMethods = new LinkedList<ExecutableElement>();
for ( ExecutableElement method : methodsIn( elements ) ) {
//TODO: consider is/has
String name = method.getSimpleName().toString();
for ( ExecutableElement method : methodsIn( elements ) ) {
//TODO: consider is/has
String name = method.getSimpleName().toString();
if ( name.startsWith( "set" ) && name.length() > 3 && method.getParameters()
.size() == 1 && method.getReturnType().getKind() == TypeKind.VOID ) {
setterMethods.add( method );
}
}
if ( name.startsWith( "set" ) && name.length() > 3 && method.getParameters()
.size() == 1 && method.getReturnType().getKind() == TypeKind.VOID ) {
setterMethods.add( method );
}
}
return setterMethods;
}
return setterMethods;
}
}

View File

@ -33,45 +33,45 @@ import org.mapstruct.Mappings;
@SupportedAnnotationTypes("org.mapstruct.Mapper")
@GeneratePrisms({
@GeneratePrism(value = Mapper.class),
@GeneratePrism(value = Mapping.class),
@GeneratePrism(value = Mappings.class)
@GeneratePrism(value = Mapper.class),
@GeneratePrism(value = Mapping.class),
@GeneratePrism(value = Mappings.class)
})
public class MappingProcessor extends AbstractProcessor {
/**
* Whether this processor claims all processed annotations exclusively or not.
*/
private static final boolean ANNOTATIONS_CLAIMED_EXCLUSIVELY = false;
/**
* Whether this processor claims all processed annotations exclusively or not.
*/
private static final boolean ANNOTATIONS_CLAIMED_EXCLUSIVELY = false;
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init( processingEnv );
}
@Override
public synchronized void init(ProcessingEnvironment processingEnv) {
super.init( processingEnv );
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported();
}
@Override
public boolean process(
final Set<? extends TypeElement> annotations,
final RoundEnvironment roundEnvironment) {
@Override
public boolean process(
final Set<? extends TypeElement> annotations,
final RoundEnvironment roundEnvironment) {
for ( TypeElement oneAnnotation : annotations ) {
for ( TypeElement oneAnnotation : annotations ) {
//Indicates that the annotation's type isn't on the class path of the compiled
//project. Let the compiler deal with that and print an appropriate error.
if ( oneAnnotation.getKind() != ElementKind.ANNOTATION_TYPE ) {
continue;
}
//Indicates that the annotation's type isn't on the class path of the compiled
//project. Let the compiler deal with that and print an appropriate error.
if ( oneAnnotation.getKind() != ElementKind.ANNOTATION_TYPE ) {
continue;
}
for ( Element oneAnnotatedElement : roundEnvironment.getElementsAnnotatedWith( oneAnnotation ) ) {
oneAnnotatedElement.accept( new MapperGenerationVisitor( processingEnv ), null );
}
}
for ( Element oneAnnotatedElement : roundEnvironment.getElementsAnnotatedWith( oneAnnotation ) ) {
oneAnnotatedElement.accept( new MapperGenerationVisitor( processingEnv ), null );
}
}
return ANNOTATIONS_CLAIMED_EXCLUSIVELY;
}
return ANNOTATIONS_CLAIMED_EXCLUSIVELY;
}
}

View File

@ -19,7 +19,7 @@ import org.mapstruct.ap.model.Type;
public interface Conversion {
String to(String sourcePropertyAccessor, Type type);
String to(String sourcePropertyAccessor, Type type);
String from(String targetPropertyAccessor, Type type);
String from(String targetPropertyAccessor, Type type);
}

View File

@ -28,94 +28,94 @@ import static org.mapstruct.ap.conversion.ReverseConversion.reverse;
public class Conversions {
private TypeUtil typeUtil;
private final Map<Key, Conversion> conversions = new HashMap<Conversions.Key, Conversion>();
private final DeclaredType enumType;
private final DeclaredType stringType;
private TypeUtil typeUtil;
private final Map<Key, Conversion> conversions = new HashMap<Conversions.Key, Conversion>();
private final DeclaredType enumType;
private final DeclaredType stringType;
public Conversions(Elements elementUtils, Types typeUtils, TypeUtil typeUtil) {
this.typeUtil = typeUtil;
public Conversions(Elements elementUtils, Types typeUtils, TypeUtil typeUtil) {
this.typeUtil = typeUtil;
this.enumType = typeUtils.getDeclaredType( elementUtils.getTypeElement( Enum.class.getCanonicalName() ) );
this.stringType = typeUtils.getDeclaredType( elementUtils.getTypeElement( String.class.getCanonicalName() ) );
this.enumType = typeUtils.getDeclaredType( elementUtils.getTypeElement( Enum.class.getCanonicalName() ) );
this.stringType = typeUtils.getDeclaredType( elementUtils.getTypeElement( String.class.getCanonicalName() ) );
register( int.class, Long.class, new IntLongConversion() );
register( int.class, String.class, new IntStringConversion() );
register( Enum.class, String.class, new EnumStringConversion() );
}
register( int.class, Long.class, new IntLongConversion() );
register( int.class, String.class, new IntStringConversion() );
register( Enum.class, String.class, new EnumStringConversion() );
}
private void register(Class<?> sourceType, Class<?> targetType, Conversion conversion) {
conversions.put( Key.forClasses( sourceType, targetType ), conversion );
conversions.put( Key.forClasses( targetType, sourceType ), reverse( conversion ) );
}
private void register(Class<?> sourceType, Class<?> targetType, Conversion conversion) {
conversions.put( Key.forClasses( sourceType, targetType ), conversion );
conversions.put( Key.forClasses( targetType, sourceType ), reverse( conversion ) );
}
public Conversion getConversion(Type sourceType, Type targetType) {
if ( sourceType.isEnumType() && targetType.equals( typeUtil.getType( stringType ) ) ) {
sourceType = typeUtil.getType( enumType );
}
public Conversion getConversion(Type sourceType, Type targetType) {
if ( sourceType.isEnumType() && targetType.equals( typeUtil.getType( stringType ) ) ) {
sourceType = typeUtil.getType( enumType );
}
return conversions.get( new Key( sourceType, targetType ) );
}
return conversions.get( new Key( sourceType, targetType ) );
}
private static class Key {
private final Type sourceType;
private final Type targetType;
private static class Key {
private final Type sourceType;
private final Type targetType;
private static Key forClasses(Class<?> sourceType, Class<?> targetType) {
return new Key( Type.forClass( sourceType ), Type.forClass( targetType ) );
}
private static Key forClasses(Class<?> sourceType, Class<?> targetType) {
return new Key( Type.forClass( sourceType ), Type.forClass( targetType ) );
}
private Key(Type sourceType, Type targetType) {
this.sourceType = sourceType;
this.targetType = targetType;
}
private Key(Type sourceType, Type targetType) {
this.sourceType = sourceType;
this.targetType = targetType;
}
@Override
public String toString() {
return "Key [sourceType=" + sourceType + ", targetType="
+ targetType + "]";
}
@Override
public String toString() {
return "Key [sourceType=" + sourceType + ", targetType="
+ targetType + "]";
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ( ( sourceType == null ) ? 0 : sourceType.hashCode() );
result = prime * result
+ ( ( targetType == null ) ? 0 : targetType.hashCode() );
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ( ( sourceType == null ) ? 0 : sourceType.hashCode() );
result = prime * result
+ ( ( targetType == null ) ? 0 : targetType.hashCode() );
return result;
}
@Override
public boolean equals(Object obj) {
if ( this == obj ) {
return true;
}
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
Key other = (Key) obj;
if ( sourceType == null ) {
if ( other.sourceType != null ) {
return false;
}
}
else if ( !sourceType.equals( other.sourceType ) ) {
return false;
}
if ( targetType == null ) {
if ( other.targetType != null ) {
return false;
}
}
else if ( !targetType.equals( other.targetType ) ) {
return false;
}
return true;
}
}
@Override
public boolean equals(Object obj) {
if ( this == obj ) {
return true;
}
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
Key other = (Key) obj;
if ( sourceType == null ) {
if ( other.sourceType != null ) {
return false;
}
}
else if ( !sourceType.equals( other.sourceType ) ) {
return false;
}
if ( targetType == null ) {
if ( other.targetType != null ) {
return false;
}
}
else if ( !targetType.equals( other.targetType ) ) {
return false;
}
return true;
}
}
}

View File

@ -19,13 +19,13 @@ import org.mapstruct.ap.model.Type;
public class EnumStringConversion implements Conversion {
@Override
public String to(String sourcePropertyAccessor, Type type) {
return sourcePropertyAccessor + " != null ? " + sourcePropertyAccessor + ".toString() : null";
}
@Override
public String to(String sourcePropertyAccessor, Type type) {
return sourcePropertyAccessor + " != null ? " + sourcePropertyAccessor + ".toString() : null";
}
@Override
public String from(String targetPropertyAccessor, Type type) {
return targetPropertyAccessor + " != null ? Enum.valueOf( " + type.getName() + ".class, " + targetPropertyAccessor + " ) : null";
}
@Override
public String from(String targetPropertyAccessor, Type type) {
return targetPropertyAccessor + " != null ? Enum.valueOf( " + type.getName() + ".class, " + targetPropertyAccessor + " ) : null";
}
}

View File

@ -19,13 +19,13 @@ import org.mapstruct.ap.model.Type;
public class IntLongConversion implements Conversion {
@Override
public String to(String sourcePropertyAccessor, Type type) {
return "Long.valueOf( " + sourcePropertyAccessor + " )";
}
@Override
public String to(String sourcePropertyAccessor, Type type) {
return "Long.valueOf( " + sourcePropertyAccessor + " )";
}
@Override
public String from(String targetPropertyAccessor, Type type) {
return targetPropertyAccessor + ".intValue()";
}
@Override
public String from(String targetPropertyAccessor, Type type) {
return targetPropertyAccessor + ".intValue()";
}
}

View File

@ -19,13 +19,13 @@ import org.mapstruct.ap.model.Type;
public class IntStringConversion implements Conversion {
@Override
public String to(String sourcePropertyAccessor, Type type) {
return "String.valueOf( " + sourcePropertyAccessor + " )";
}
@Override
public String to(String sourcePropertyAccessor, Type type) {
return "String.valueOf( " + sourcePropertyAccessor + " )";
}
@Override
public String from(String targetPropertyAccessor, Type type) {
return "Integer.parseInt( " + targetPropertyAccessor + " )";
}
@Override
public String from(String targetPropertyAccessor, Type type) {
return "Integer.parseInt( " + targetPropertyAccessor + " )";
}
}

View File

@ -19,23 +19,23 @@ import org.mapstruct.ap.model.Type;
public class ReverseConversion implements Conversion {
private Conversion conversion;
private Conversion conversion;
public static ReverseConversion reverse(Conversion conversion) {
return new ReverseConversion( conversion );
}
public static ReverseConversion reverse(Conversion conversion) {
return new ReverseConversion( conversion );
}
private ReverseConversion(Conversion conversion) {
this.conversion = conversion;
}
private ReverseConversion(Conversion conversion) {
this.conversion = conversion;
}
@Override
public String to(String sourcePropertyAccessor, Type type) {
return conversion.from( sourcePropertyAccessor, type );
}
@Override
public String to(String sourcePropertyAccessor, Type type) {
return conversion.from( sourcePropertyAccessor, type );
}
@Override
public String from(String targetPropertyAccessor, Type type) {
return conversion.to( targetPropertyAccessor, type );
}
@Override
public String from(String targetPropertyAccessor, Type type) {
return conversion.to( targetPropertyAccessor, type );
}
}

View File

@ -19,56 +19,56 @@ import java.util.List;
public class BeanMapping {
private final Type sourceType;
private final Type targetType;
private final List<PropertyMapping> propertyMappings;
private final MappingMethod mappingMethod;
private final MappingMethod reverseMappingMethod;
private final boolean isIterableMapping;
private final Type sourceType;
private final Type targetType;
private final List<PropertyMapping> propertyMappings;
private final MappingMethod mappingMethod;
private final MappingMethod reverseMappingMethod;
private final boolean isIterableMapping;
public BeanMapping(Type sourceType, Type targetType, List<PropertyMapping> propertyMappings, MappingMethod mappingMethod,
MappingMethod reverseMappingMethod) {
this.sourceType = sourceType;
this.targetType = targetType;
this.propertyMappings = propertyMappings;
this.mappingMethod = mappingMethod;
this.reverseMappingMethod = reverseMappingMethod;
this.isIterableMapping = mappingMethod.getElementMappingMethod() != null;
}
public BeanMapping(Type sourceType, Type targetType, List<PropertyMapping> propertyMappings, MappingMethod mappingMethod,
MappingMethod reverseMappingMethod) {
this.sourceType = sourceType;
this.targetType = targetType;
this.propertyMappings = propertyMappings;
this.mappingMethod = mappingMethod;
this.reverseMappingMethod = reverseMappingMethod;
this.isIterableMapping = mappingMethod.getElementMappingMethod() != null;
}
public Type getSourceType() {
return sourceType;
}
public Type getSourceType() {
return sourceType;
}
public Type getTargetType() {
return targetType;
}
public Type getTargetType() {
return targetType;
}
public List<PropertyMapping> getPropertyMappings() {
return propertyMappings;
}
public List<PropertyMapping> getPropertyMappings() {
return propertyMappings;
}
public MappingMethod getMappingMethod() {
return mappingMethod;
}
public MappingMethod getMappingMethod() {
return mappingMethod;
}
public MappingMethod getReverseMappingMethod() {
return reverseMappingMethod;
}
public MappingMethod getReverseMappingMethod() {
return reverseMappingMethod;
}
public boolean getIterableMapping() {
return isIterableMapping;
}
public boolean getIterableMapping() {
return isIterableMapping;
}
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
@Override
public String toString() {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append( sourceType );
stringBuilder.append( " <=> " );
stringBuilder.append( targetType );
stringBuilder.append( sourceType );
stringBuilder.append( " <=> " );
stringBuilder.append( targetType );
return stringBuilder.toString();
}
return stringBuilder.toString();
}
}

View File

@ -19,38 +19,38 @@ import java.util.List;
public class Mapper {
private final String packageName;
private final String interfaceName;
private final String implementationName;
private final List<BeanMapping> beanMappings;
private final List<Type> usedMapperTypes;
private final String packageName;
private final String interfaceName;
private final String implementationName;
private final List<BeanMapping> beanMappings;
private final List<Type> usedMapperTypes;
public Mapper(String packageName, String interfaceName,
String implementationName, List<BeanMapping> beanMappings, List<Type> usedMapperTypes) {
this.packageName = packageName;
this.interfaceName = interfaceName;
this.implementationName = implementationName;
this.beanMappings = beanMappings;
this.usedMapperTypes = usedMapperTypes;
}
public Mapper(String packageName, String interfaceName,
String implementationName, List<BeanMapping> beanMappings, List<Type> usedMapperTypes) {
this.packageName = packageName;
this.interfaceName = interfaceName;
this.implementationName = implementationName;
this.beanMappings = beanMappings;
this.usedMapperTypes = usedMapperTypes;
}
public String getPackageName() {
return packageName;
}
public String getPackageName() {
return packageName;
}
public String getInterfaceName() {
return interfaceName;
}
public String getInterfaceName() {
return interfaceName;
}
public String getImplementationName() {
return implementationName;
}
public String getImplementationName() {
return implementationName;
}
public List<BeanMapping> getBeanMappings() {
return beanMappings;
}
public List<BeanMapping> getBeanMappings() {
return beanMappings;
}
public List<Type> getUsedMapperTypes() {
return usedMapperTypes;
}
public List<Type> getUsedMapperTypes() {
return usedMapperTypes;
}
}

View File

@ -17,42 +17,42 @@ package org.mapstruct.ap.model;
public class MappingMethod {
private final Type declaringMapper;
private final String name;
private final String parameterName;
private final MappingMethod elementMappingMethod;
private final Type declaringMapper;
private final String name;
private final String parameterName;
private final MappingMethod elementMappingMethod;
public MappingMethod(Type declaringMapper, String name, String parameterName) {
this.declaringMapper = declaringMapper;
this.name = name;
this.parameterName = parameterName;
this.elementMappingMethod = null;
}
public MappingMethod(Type declaringMapper, String name, String parameterName) {
this.declaringMapper = declaringMapper;
this.name = name;
this.parameterName = parameterName;
this.elementMappingMethod = null;
}
public MappingMethod(Type declaringMapper, String name, String parameterName, MappingMethod elementMappingMethod) {
this.declaringMapper = declaringMapper;
this.name = name;
this.parameterName = parameterName;
this.elementMappingMethod = elementMappingMethod;
}
public MappingMethod(Type declaringMapper, String name, String parameterName, MappingMethod elementMappingMethod) {
this.declaringMapper = declaringMapper;
this.name = name;
this.parameterName = parameterName;
this.elementMappingMethod = elementMappingMethod;
}
public Type getDeclaringMapper() {
return declaringMapper;
}
public Type getDeclaringMapper() {
return declaringMapper;
}
public String getName() {
return name;
}
public String getName() {
return name;
}
public String getParameterName() {
return parameterName;
}
public String getParameterName() {
return parameterName;
}
public MappingMethod getElementMappingMethod() {
return elementMappingMethod;
}
public MappingMethod getElementMappingMethod() {
return elementMappingMethod;
}
public boolean isGenerationRequired() {
return declaringMapper == null;
}
public boolean isGenerationRequired() {
return declaringMapper == null;
}
}

View File

@ -17,55 +17,55 @@ package org.mapstruct.ap.model;
public class PropertyMapping {
private final String sourceName;
private final Type sourceType;
private final String targetName;
private final Type targetType;
private final MappingMethod mappingMethod;
private final MappingMethod reverseMappingMethod;
private final String toConversion;
private final String fromConversion;
private final String sourceName;
private final Type sourceType;
private final String targetName;
private final Type targetType;
private final MappingMethod mappingMethod;
private final MappingMethod reverseMappingMethod;
private final String toConversion;
private final String fromConversion;
public PropertyMapping(String sourceName, Type sourceType, String targetName, Type targetType, MappingMethod mappingMethod, MappingMethod reverseMappingMethod, String toConversion, String fromConversion) {
this.sourceName = sourceName;
this.sourceType = sourceType;
this.targetName = targetName;
this.targetType = targetType;
this.mappingMethod = mappingMethod;
this.reverseMappingMethod = reverseMappingMethod;
this.toConversion = toConversion;
this.fromConversion = fromConversion;
}
public PropertyMapping(String sourceName, Type sourceType, String targetName, Type targetType, MappingMethod mappingMethod, MappingMethod reverseMappingMethod, String toConversion, String fromConversion) {
this.sourceName = sourceName;
this.sourceType = sourceType;
this.targetName = targetName;
this.targetType = targetType;
this.mappingMethod = mappingMethod;
this.reverseMappingMethod = reverseMappingMethod;
this.toConversion = toConversion;
this.fromConversion = fromConversion;
}
public String getSourceName() {
return sourceName;
}
public String getSourceName() {
return sourceName;
}
public Type getSourceType() {
return sourceType;
}
public Type getSourceType() {
return sourceType;
}
public String getTargetName() {
return targetName;
}
public String getTargetName() {
return targetName;
}
public Type getTargetType() {
return targetType;
}
public Type getTargetType() {
return targetType;
}
public MappingMethod getMappingMethod() {
return mappingMethod;
}
public MappingMethod getMappingMethod() {
return mappingMethod;
}
public MappingMethod getReverseMappingMethod() {
return reverseMappingMethod;
}
public MappingMethod getReverseMappingMethod() {
return reverseMappingMethod;
}
public String getToConversion() {
return toConversion;
}
public String getToConversion() {
return toConversion;
}
public String getFromConversion() {
return fromConversion;
}
public String getFromConversion() {
return fromConversion;
}
}

View File

@ -26,122 +26,122 @@ import java.util.Set;
*/
public class Type {
private final static Set<String> primitiveTypeNames = new HashSet<String>(
Arrays.asList( "boolean", "char", "byte", "short", "int", "long", "float", "double" )
);
private final static Set<String> primitiveTypeNames = new HashSet<String>(
Arrays.asList( "boolean", "char", "byte", "short", "int", "long", "float", "double" )
);
private final String packageName;
private final String name;
private final Type elementType;
private final boolean isEnumType;
private final String packageName;
private final String name;
private final Type elementType;
private final boolean isEnumType;
public static Type forClass(Class<?> clazz) {
Package pakkage = clazz.getPackage();
public static Type forClass(Class<?> clazz) {
Package pakkage = clazz.getPackage();
if ( pakkage != null ) {
return new Type( pakkage.getName(), clazz.getSimpleName(), null, clazz.isEnum() );
}
else {
return new Type( clazz.getSimpleName() );
}
}
if ( pakkage != null ) {
return new Type( pakkage.getName(), clazz.getSimpleName(), null, clazz.isEnum() );
}
else {
return new Type( clazz.getSimpleName() );
}
}
public Type(String name) {
this( null, name, null, false );
}
public Type(String name) {
this( null, name, null, false );
}
public Type(String packageName, String name) {
this( packageName, name, null, false );
}
public Type(String packageName, String name) {
this( packageName, name, null, false );
}
public Type(String packageName, String name, Type elementType, boolean isEnumType) {
this.packageName = packageName;
this.name = name;
this.elementType = elementType;
this.isEnumType = isEnumType;
}
public Type(String packageName, String name, Type elementType, boolean isEnumType) {
this.packageName = packageName;
this.name = name;
this.elementType = elementType;
this.isEnumType = isEnumType;
}
public String getPackageName() {
return packageName;
}
public String getPackageName() {
return packageName;
}
public String getName() {
return name;
}
public String getName() {
return name;
}
public Type getElementType() {
return elementType;
}
public Type getElementType() {
return elementType;
}
public boolean isPrimitive() {
return packageName == null && primitiveTypeNames.contains( name );
}
public boolean isPrimitive() {
return packageName == null && primitiveTypeNames.contains( name );
}
public boolean isEnumType() {
return isEnumType;
}
public boolean isEnumType() {
return isEnumType;
}
@Override
public String toString() {
if ( packageName == null ) {
return name;
}
else if ( elementType == null ) {
return packageName + "." + name;
}
else {
return packageName + "." + name + "<" + elementType + ">";
}
}
@Override
public String toString() {
if ( packageName == null ) {
return name;
}
else if ( elementType == null ) {
return packageName + "." + name;
}
else {
return packageName + "." + name + "<" + elementType + ">";
}
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ( ( elementType == null ) ? 0 : elementType.hashCode() );
result = prime * result + ( ( name == null ) ? 0 : name.hashCode() );
result = prime * result
+ ( ( packageName == null ) ? 0 : packageName.hashCode() );
return result;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result
+ ( ( elementType == null ) ? 0 : elementType.hashCode() );
result = prime * result + ( ( name == null ) ? 0 : name.hashCode() );
result = prime * result
+ ( ( packageName == null ) ? 0 : packageName.hashCode() );
return result;
}
@Override
public boolean equals(Object obj) {
if ( this == obj ) {
return true;
}
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
Type other = (Type) obj;
if ( elementType == null ) {
if ( other.elementType != null ) {
return false;
}
}
else if ( !elementType.equals( other.elementType ) ) {
return false;
}
if ( name == null ) {
if ( other.name != null ) {
return false;
}
}
else if ( !name.equals( other.name ) ) {
return false;
}
if ( packageName == null ) {
if ( other.packageName != null ) {
return false;
}
}
else if ( !packageName.equals( other.packageName ) ) {
return false;
}
return true;
}
@Override
public boolean equals(Object obj) {
if ( this == obj ) {
return true;
}
if ( obj == null ) {
return false;
}
if ( getClass() != obj.getClass() ) {
return false;
}
Type other = (Type) obj;
if ( elementType == null ) {
if ( other.elementType != null ) {
return false;
}
}
else if ( !elementType.equals( other.elementType ) ) {
return false;
}
if ( name == null ) {
if ( other.name != null ) {
return false;
}
}
else if ( !name.equals( other.name ) ) {
return false;
}
if ( packageName == null ) {
if ( other.packageName != null ) {
return false;
}
}
else if ( !packageName.equals( other.packageName ) ) {
return false;
}
return true;
}
}

View File

@ -19,36 +19,36 @@ import org.mapstruct.ap.model.Type;
public class MappedProperty {
private final String sourceName;
private final Type sourceType;
private final String targetName;
private final Type targetType;
private final String sourceName;
private final Type sourceType;
private final String targetName;
private final Type targetType;
public MappedProperty(String sourceName, Type sourceType, String targetName, Type targetType) {
this.sourceName = sourceName;
this.sourceType = sourceType;
this.targetName = targetName;
this.targetType = targetType;
}
public MappedProperty(String sourceName, Type sourceType, String targetName, Type targetType) {
this.sourceName = sourceName;
this.sourceType = sourceType;
this.targetName = targetName;
this.targetType = targetType;
}
public String getSourceName() {
return sourceName;
}
public String getSourceName() {
return sourceName;
}
public Type getSourceType() {
return sourceType;
}
public Type getSourceType() {
return sourceType;
}
public String getTargetName() {
return targetName;
}
public String getTargetName() {
return targetName;
}
public Type getTargetType() {
return targetType;
}
public Type getTargetType() {
return targetType;
}
@Override
public String toString() {
return sourceType + " " + sourceName + " <=> " + targetType + " " + targetName;
}
@Override
public String toString() {
return sourceType + " " + sourceName + " <=> " + targetType + " " + targetName;
}
}

View File

@ -17,19 +17,19 @@ package org.mapstruct.ap.model.source;
public class Mapping {
private final String sourceName;
private final String targetName;
private final String sourceName;
private final String targetName;
public Mapping(String sourceName, String targetName) {
this.sourceName = sourceName;
this.targetName = targetName;
}
public Mapping(String sourceName, String targetName) {
this.sourceName = sourceName;
this.targetName = targetName;
}
public String getSourceName() {
return sourceName;
}
public String getSourceName() {
return sourceName;
}
public String getTargetName() {
return targetName;
}
public String getTargetName() {
return targetName;
}
}

View File

@ -22,62 +22,62 @@ import org.mapstruct.ap.model.Type;
public class Method {
private final Type declaringMapper;
private final String name;
private final String parameterName;
private final Type sourceType;
private final Type targetType;
private final List<MappedProperty> mappedProperties;
private final Type declaringMapper;
private final String name;
private final String parameterName;
private final Type sourceType;
private final Type targetType;
private final List<MappedProperty> mappedProperties;
public Method(String name, String parameterName, Type sourceType, Type targetType, List<MappedProperty> mappedProperties) {
this( null, name, parameterName, sourceType, targetType, mappedProperties );
}
public Method(String name, String parameterName, Type sourceType, Type targetType, List<MappedProperty> mappedProperties) {
this( null, name, parameterName, sourceType, targetType, mappedProperties );
}
public Method(Type declaringMapper, String name, String parameterName, Type sourceType, Type targetType, List<MappedProperty> mappedProperties) {
this.declaringMapper = declaringMapper;
this.name = name;
this.parameterName = parameterName;
this.sourceType = sourceType;
this.targetType = targetType;
this.mappedProperties = mappedProperties;
}
public Method(Type declaringMapper, String name, String parameterName, Type sourceType, Type targetType, List<MappedProperty> mappedProperties) {
this.declaringMapper = declaringMapper;
this.name = name;
this.parameterName = parameterName;
this.sourceType = sourceType;
this.targetType = targetType;
this.mappedProperties = mappedProperties;
}
public Type getDeclaringMapper() {
return declaringMapper;
}
public Type getDeclaringMapper() {
return declaringMapper;
}
public String getName() {
return name;
}
public String getName() {
return name;
}
public String getParameterName() {
return parameterName;
}
public String getParameterName() {
return parameterName;
}
public Type getSourceType() {
return sourceType;
}
public Type getSourceType() {
return sourceType;
}
public Type getTargetType() {
return targetType;
}
public Type getTargetType() {
return targetType;
}
public List<MappedProperty> getMappedProperties() {
return mappedProperties;
}
public List<MappedProperty> getMappedProperties() {
return mappedProperties;
}
public boolean reverses(Method method) {
return
equals( sourceType, method.getTargetType() ) &&
equals( targetType, method.getSourceType() );
}
public boolean reverses(Method method) {
return
equals( sourceType, method.getTargetType() ) &&
equals( targetType, method.getSourceType() );
}
private boolean equals(Object o1, Object o2) {
return ( o1 == null && o2 == null ) || ( o1 != null ) && o1.equals( o2 );
}
private boolean equals(Object o1, Object o2) {
return ( o1 == null && o2 == null ) || ( o1 != null ) && o1.equals( o2 );
}
@Override
public String toString() {
return targetType + " " + name + "(" + sourceType + " " + parameterName + ")";
}
@Override
public String toString() {
return targetType + " " + name + "(" + sourceType + " " + parameterName + ")";
}
}

View File

@ -19,19 +19,19 @@ import org.mapstruct.ap.model.Type;
public class Parameter {
private final String name;
private final Type type;
private final String name;
private final Type type;
public Parameter(String name, Type type) {
this.name = name;
this.type = type;
}
public Parameter(String name, Type type) {
this.name = name;
this.type = type;
}
public String getName() {
return name;
}
public String getName() {
return name;
}
public Type getType() {
return type;
}
public Type getType() {
return type;
}
}

View File

@ -26,39 +26,39 @@ import org.mapstruct.ap.model.Type;
public class TypeUtil {
private final Elements elementUtils;
private final Types typeUtils;
private final Elements elementUtils;
private final Types typeUtils;
public TypeUtil(Elements elementUtils, Types typeUtils) {
this.elementUtils = elementUtils;
this.typeUtils = typeUtils;
}
public TypeUtil(Elements elementUtils, Types typeUtils) {
this.elementUtils = elementUtils;
this.typeUtils = typeUtils;
}
public Type getType(DeclaredType type) {
Type elementType = isIterableType( type ) ? retrieveType( type.getTypeArguments().iterator().next() ) : null;
public Type getType(DeclaredType type) {
Type elementType = isIterableType( type ) ? retrieveType( type.getTypeArguments().iterator().next() ) : null;
return new Type(
elementUtils.getPackageOf( type.asElement() ).toString(),
type.asElement().getSimpleName().toString(),
elementType,
type.asElement().getKind() == ElementKind.ENUM
);
}
return new Type(
elementUtils.getPackageOf( type.asElement() ).toString(),
type.asElement().getSimpleName().toString(),
elementType,
type.asElement().getKind() == ElementKind.ENUM
);
}
private boolean isIterableType(DeclaredType type) {
TypeMirror iterableType = typeUtils.getDeclaredType( elementUtils.getTypeElement( Iterable.class.getCanonicalName() ) );
return typeUtils.isSubtype( type, iterableType );
}
private boolean isIterableType(DeclaredType type) {
TypeMirror iterableType = typeUtils.getDeclaredType( elementUtils.getTypeElement( Iterable.class.getCanonicalName() ) );
return typeUtils.isSubtype( type, iterableType );
}
public Type retrieveType(TypeMirror mirror) {
if ( mirror == null ) {
return null;
}
else if ( mirror.getKind() == TypeKind.DECLARED ) {
return getType( ( (DeclaredType) mirror ) );
}
else {
return new Type( mirror.toString() );
}
}
public Type retrieveType(TypeMirror mirror) {
if ( mirror == null ) {
return null;
}
else if ( mirror.getKind() == TypeKind.DECLARED ) {
return getType( ( (DeclaredType) mirror ) );
}
else {
return new Type( mirror.toString() );
}
}
}

View File

@ -24,35 +24,35 @@ import freemarker.template.Template;
public class ModelWriter {
private static final Configuration configuration;
private static final Configuration configuration;
private final String templateName;
private final String templateName;
static {
configuration = new Configuration();
configuration.setClassForTemplateLoading( ModelWriter.class, "/" );
configuration.setObjectWrapper( new DefaultObjectWrapper() );
}
static {
configuration = new Configuration();
configuration.setClassForTemplateLoading( ModelWriter.class, "/" );
configuration.setObjectWrapper( new DefaultObjectWrapper() );
}
public ModelWriter(String templateName) {
this.templateName = templateName;
}
public ModelWriter(String templateName) {
this.templateName = templateName;
}
public void writeModel(JavaFileObject sourceFile, Object model) {
public void writeModel(JavaFileObject sourceFile, Object model) {
try {
BufferedWriter writer = new BufferedWriter( sourceFile.openWriter() );
try {
BufferedWriter writer = new BufferedWriter( sourceFile.openWriter() );
Template template = configuration.getTemplate( templateName );
template.process( model, writer );
writer.flush();
writer.close();
}
catch ( RuntimeException e ) {
throw e;
}
catch ( Exception e ) {
throw new RuntimeException( e );
}
}
Template template = configuration.getTemplate( templateName );
template.process( model, writer );
writer.flush();
writer.close();
}
catch ( RuntimeException e ) {
throw e;
}
catch ( Exception e ) {
throw new RuntimeException( e );
}
}
}

View File

@ -37,280 +37,280 @@ import static org.fest.assertions.Assertions.assertThat;
public class CarMapperTest extends MapperTestBase {
private DiagnosticCollector<JavaFileObject> diagnostics;
private DiagnosticCollector<JavaFileObject> diagnostics;
public CarMapperTest() {
super( "mapstruct.jar" );
}
public CarMapperTest() {
super( "mapstruct.jar" );
}
@BeforeMethod
public void generateMapperImplementation() {
diagnostics = new DiagnosticCollector<JavaFileObject>();
File[] sourceFiles = getSourceFiles(
Car.class,
CarDto.class,
Person.class,
PersonDto.class,
CarMapper.class,
Category.class,
DateMapper.class
);
@BeforeMethod
public void generateMapperImplementation() {
diagnostics = new DiagnosticCollector<JavaFileObject>();
File[] sourceFiles = getSourceFiles(
Car.class,
CarDto.class,
Person.class,
PersonDto.class,
CarMapper.class,
Category.class,
DateMapper.class
);
boolean compilationSuccessful = compile( diagnostics, sourceFiles );
boolean compilationSuccessful = compile( diagnostics, sourceFiles );
assertThat( compilationSuccessful ).describedAs( "Compilation failed: " + diagnostics.getDiagnostics() )
.isTrue();
}
assertThat( compilationSuccessful ).describedAs( "Compilation failed: " + diagnostics.getDiagnostics() )
.isTrue();
}
@Test
public void shouldProvideMapperInstance() throws Exception {
assertThat( CarMapper.INSTANCE ).isNotNull();
}
@Test
public void shouldProvideMapperInstance() throws Exception {
assertThat( CarMapper.INSTANCE ).isNotNull();
}
@Test
public void shouldMapAttributeByName() {
//given
Car car = new Car(
"Morris",
2,
new GregorianCalendar( 1980, 0, 1 ).getTime(),
new Person( "Bob" ),
new ArrayList<Person>()
);
@Test
public void shouldMapAttributeByName() {
//given
Car car = new Car(
"Morris",
2,
new GregorianCalendar( 1980, 0, 1 ).getTime(),
new Person( "Bob" ),
new ArrayList<Person>()
);
//when
CarDto carDto = CarMapper.INSTANCE.carToCarDto( car );
//when
CarDto carDto = CarMapper.INSTANCE.carToCarDto( car );
//then
assertThat( carDto ).isNotNull();
assertThat( carDto.getMake() ).isEqualTo( car.getMake() );
}
//then
assertThat( carDto ).isNotNull();
assertThat( carDto.getMake() ).isEqualTo( car.getMake() );
}
@Test
public void shouldMapReferenceAttribute() {
//given
Car car = new Car(
"Morris",
2,
new GregorianCalendar( 1980, 0, 1 ).getTime(),
new Person( "Bob" ),
new ArrayList<Person>()
);
@Test
public void shouldMapReferenceAttribute() {
//given
Car car = new Car(
"Morris",
2,
new GregorianCalendar( 1980, 0, 1 ).getTime(),
new Person( "Bob" ),
new ArrayList<Person>()
);
//when
CarDto carDto = CarMapper.INSTANCE.carToCarDto( car );
//when
CarDto carDto = CarMapper.INSTANCE.carToCarDto( car );
//then
assertThat( carDto ).isNotNull();
assertThat( carDto.getDriver() ).isNotNull();
assertThat( carDto.getDriver().getName() ).isEqualTo( "Bob" );
}
//then
assertThat( carDto ).isNotNull();
assertThat( carDto.getDriver() ).isNotNull();
assertThat( carDto.getDriver().getName() ).isEqualTo( "Bob" );
}
@Test
public void shouldReverseMapReferenceAttribute() {
//given
CarDto carDto = new CarDto( "Morris", 2, "1980", new PersonDto( "Bob" ), new ArrayList<PersonDto>() );
@Test
public void shouldReverseMapReferenceAttribute() {
//given
CarDto carDto = new CarDto( "Morris", 2, "1980", new PersonDto( "Bob" ), new ArrayList<PersonDto>() );
//when
Car car = CarMapper.INSTANCE.carDtoToCar( carDto );
//when
Car car = CarMapper.INSTANCE.carDtoToCar( carDto );
//then
assertThat( car ).isNotNull();
assertThat( car.getDriver() ).isNotNull();
assertThat( car.getDriver().getName() ).isEqualTo( "Bob" );
}
//then
assertThat( car ).isNotNull();
assertThat( car.getDriver() ).isNotNull();
assertThat( car.getDriver().getName() ).isEqualTo( "Bob" );
}
@Test
public void shouldMapAttributeWithCustomMapping() {
//given
Car car = new Car(
"Morris",
2,
new GregorianCalendar( 1980, 0, 1 ).getTime(),
new Person( "Bob" ),
new ArrayList<Person>()
);
@Test
public void shouldMapAttributeWithCustomMapping() {
//given
Car car = new Car(
"Morris",
2,
new GregorianCalendar( 1980, 0, 1 ).getTime(),
new Person( "Bob" ),
new ArrayList<Person>()
);
//when
CarDto carDto = CarMapper.INSTANCE.carToCarDto( car );
//when
CarDto carDto = CarMapper.INSTANCE.carToCarDto( car );
//then
assertThat( carDto ).isNotNull();
assertThat( carDto.getSeatCount() ).isEqualTo( car.getNumberOfSeats() );
}
//then
assertThat( carDto ).isNotNull();
assertThat( carDto.getSeatCount() ).isEqualTo( car.getNumberOfSeats() );
}
@Test
public void shouldConsiderCustomMappingForReverseMapping() {
//given
CarDto carDto = new CarDto( "Morris", 2, "1980", new PersonDto( "Bob" ), new ArrayList<PersonDto>() );
@Test
public void shouldConsiderCustomMappingForReverseMapping() {
//given
CarDto carDto = new CarDto( "Morris", 2, "1980", new PersonDto( "Bob" ), new ArrayList<PersonDto>() );
//when
Car car = CarMapper.INSTANCE.carDtoToCar( carDto );
//when
Car car = CarMapper.INSTANCE.carDtoToCar( carDto );
//then
assertThat( car ).isNotNull();
assertThat( car.getNumberOfSeats() ).isEqualTo( carDto.getSeatCount() );
}
//then
assertThat( car ).isNotNull();
assertThat( car.getNumberOfSeats() ).isEqualTo( carDto.getSeatCount() );
}
@Test
public void shouldApplyConverter() {
//given
Car car = new Car(
"Morris",
2,
new GregorianCalendar( 1980, 0, 1 ).getTime(),
new Person( "Bob" ),
new ArrayList<Person>()
);
@Test
public void shouldApplyConverter() {
//given
Car car = new Car(
"Morris",
2,
new GregorianCalendar( 1980, 0, 1 ).getTime(),
new Person( "Bob" ),
new ArrayList<Person>()
);
//when
CarDto carDto = CarMapper.INSTANCE.carToCarDto( car );
//when
CarDto carDto = CarMapper.INSTANCE.carToCarDto( car );
//then
assertThat( carDto ).isNotNull();
assertThat( carDto.getManufacturingYear() ).isEqualTo( "1980" );
}
//then
assertThat( carDto ).isNotNull();
assertThat( carDto.getManufacturingYear() ).isEqualTo( "1980" );
}
@Test
public void shouldApplyConverterForReverseMapping() {
//given
CarDto carDto = new CarDto( "Morris", 2, "1980", new PersonDto( "Bob" ), new ArrayList<PersonDto>() );
@Test
public void shouldApplyConverterForReverseMapping() {
//given
CarDto carDto = new CarDto( "Morris", 2, "1980", new PersonDto( "Bob" ), new ArrayList<PersonDto>() );
//when
Car car = CarMapper.INSTANCE.carDtoToCar( carDto );
//when
Car car = CarMapper.INSTANCE.carDtoToCar( carDto );
//then
assertThat( car ).isNotNull();
assertThat( car.getManufacturingDate() ).isEqualTo( new GregorianCalendar( 1980, 0, 1 ).getTime() );
}
//then
assertThat( car ).isNotNull();
assertThat( car.getManufacturingDate() ).isEqualTo( new GregorianCalendar( 1980, 0, 1 ).getTime() );
}
@Test
public void shouldMapIterable() {
//given
Car car1 = new Car(
"Morris",
2,
new GregorianCalendar( 1980, 0, 1 ).getTime(),
new Person( "Bob" ),
new ArrayList<Person>()
);
Car car2 = new Car(
"Railton",
4,
new GregorianCalendar( 1934, 0, 1 ).getTime(),
new Person( "Bill" ),
new ArrayList<Person>()
);
@Test
public void shouldMapIterable() {
//given
Car car1 = new Car(
"Morris",
2,
new GregorianCalendar( 1980, 0, 1 ).getTime(),
new Person( "Bob" ),
new ArrayList<Person>()
);
Car car2 = new Car(
"Railton",
4,
new GregorianCalendar( 1934, 0, 1 ).getTime(),
new Person( "Bill" ),
new ArrayList<Person>()
);
//when
List<CarDto> dtos = CarMapper.INSTANCE.carsToCarDtos( new ArrayList<Car>( Arrays.asList( car1, car2 ) ) );
//when
List<CarDto> dtos = CarMapper.INSTANCE.carsToCarDtos( new ArrayList<Car>( Arrays.asList( car1, car2 ) ) );
//then
assertThat( dtos ).isNotNull();
assertThat( dtos ).hasSize( 2 );
//then
assertThat( dtos ).isNotNull();
assertThat( dtos ).hasSize( 2 );
assertThat( dtos.get( 0 ).getMake() ).isEqualTo( "Morris" );
assertThat( dtos.get( 0 ).getSeatCount() ).isEqualTo( 2 );
assertThat( dtos.get( 0 ).getManufacturingYear() ).isEqualTo( "1980" );
assertThat( dtos.get( 0 ).getDriver().getName() ).isEqualTo( "Bob" );
assertThat( dtos.get( 0 ).getMake() ).isEqualTo( "Morris" );
assertThat( dtos.get( 0 ).getSeatCount() ).isEqualTo( 2 );
assertThat( dtos.get( 0 ).getManufacturingYear() ).isEqualTo( "1980" );
assertThat( dtos.get( 0 ).getDriver().getName() ).isEqualTo( "Bob" );
assertThat( dtos.get( 1 ).getMake() ).isEqualTo( "Railton" );
assertThat( dtos.get( 1 ).getSeatCount() ).isEqualTo( 4 );
assertThat( dtos.get( 1 ).getManufacturingYear() ).isEqualTo( "1934" );
assertThat( dtos.get( 1 ).getDriver().getName() ).isEqualTo( "Bill" );
}
assertThat( dtos.get( 1 ).getMake() ).isEqualTo( "Railton" );
assertThat( dtos.get( 1 ).getSeatCount() ).isEqualTo( 4 );
assertThat( dtos.get( 1 ).getManufacturingYear() ).isEqualTo( "1934" );
assertThat( dtos.get( 1 ).getDriver().getName() ).isEqualTo( "Bill" );
}
@Test
public void shouldReverseMapIterable() {
//given
CarDto car1 = new CarDto( "Morris", 2, "1980", new PersonDto( "Bob" ), new ArrayList<PersonDto>() );
CarDto car2 = new CarDto( "Railton", 4, "1934", new PersonDto( "Bill" ), new ArrayList<PersonDto>() );
@Test
public void shouldReverseMapIterable() {
//given
CarDto car1 = new CarDto( "Morris", 2, "1980", new PersonDto( "Bob" ), new ArrayList<PersonDto>() );
CarDto car2 = new CarDto( "Railton", 4, "1934", new PersonDto( "Bill" ), new ArrayList<PersonDto>() );
//when
List<Car> cars = CarMapper.INSTANCE.carDtosToCars( new ArrayList<CarDto>( Arrays.asList( car1, car2 ) ) );
//when
List<Car> cars = CarMapper.INSTANCE.carDtosToCars( new ArrayList<CarDto>( Arrays.asList( car1, car2 ) ) );
//then
assertThat( cars ).isNotNull();
assertThat( cars ).hasSize( 2 );
//then
assertThat( cars ).isNotNull();
assertThat( cars ).hasSize( 2 );
assertThat( cars.get( 0 ).getMake() ).isEqualTo( "Morris" );
assertThat( cars.get( 0 ).getNumberOfSeats() ).isEqualTo( 2 );
assertThat( cars.get( 0 ).getManufacturingDate() ).isEqualTo( new GregorianCalendar( 1980, 0, 1 ).getTime() );
assertThat( cars.get( 0 ).getDriver().getName() ).isEqualTo( "Bob" );
assertThat( cars.get( 0 ).getMake() ).isEqualTo( "Morris" );
assertThat( cars.get( 0 ).getNumberOfSeats() ).isEqualTo( 2 );
assertThat( cars.get( 0 ).getManufacturingDate() ).isEqualTo( new GregorianCalendar( 1980, 0, 1 ).getTime() );
assertThat( cars.get( 0 ).getDriver().getName() ).isEqualTo( "Bob" );
assertThat( cars.get( 1 ).getMake() ).isEqualTo( "Railton" );
assertThat( cars.get( 1 ).getNumberOfSeats() ).isEqualTo( 4 );
assertThat( cars.get( 1 ).getManufacturingDate() ).isEqualTo( new GregorianCalendar( 1934, 0, 1 ).getTime() );
assertThat( cars.get( 1 ).getDriver().getName() ).isEqualTo( "Bill" );
}
assertThat( cars.get( 1 ).getMake() ).isEqualTo( "Railton" );
assertThat( cars.get( 1 ).getNumberOfSeats() ).isEqualTo( 4 );
assertThat( cars.get( 1 ).getManufacturingDate() ).isEqualTo( new GregorianCalendar( 1934, 0, 1 ).getTime() );
assertThat( cars.get( 1 ).getDriver().getName() ).isEqualTo( "Bill" );
}
@Test
public void shouldMapIterableAttribute() {
//given
Car car = new Car(
"Morris",
2,
new GregorianCalendar( 1980, 0, 1 ).getTime(),
new Person( "Bob" ),
new ArrayList<Person>( Arrays.asList( new Person( "Alice" ), new Person( "Bill" ) ) )
);
@Test
public void shouldMapIterableAttribute() {
//given
Car car = new Car(
"Morris",
2,
new GregorianCalendar( 1980, 0, 1 ).getTime(),
new Person( "Bob" ),
new ArrayList<Person>( Arrays.asList( new Person( "Alice" ), new Person( "Bill" ) ) )
);
//when
CarDto dto = CarMapper.INSTANCE.carToCarDto( car );
//when
CarDto dto = CarMapper.INSTANCE.carToCarDto( car );
//then
assertThat( dto ).isNotNull();
//then
assertThat( dto ).isNotNull();
assertThat( dto.getPassengers() ).hasSize( 2 );
assertThat( dto.getPassengers().get( 0 ).getName() ).isEqualTo( "Alice" );
assertThat( dto.getPassengers().get( 1 ).getName() ).isEqualTo( "Bill" );
}
assertThat( dto.getPassengers() ).hasSize( 2 );
assertThat( dto.getPassengers().get( 0 ).getName() ).isEqualTo( "Alice" );
assertThat( dto.getPassengers().get( 1 ).getName() ).isEqualTo( "Bill" );
}
@Test
public void shouldReverseMapIterableAttribute() {
//given
CarDto carDto = new CarDto(
"Morris",
2,
"1980",
new PersonDto( "Bob" ),
new ArrayList<PersonDto>( Arrays.asList( new PersonDto( "Alice" ), new PersonDto( "Bill" ) ) )
);
@Test
public void shouldReverseMapIterableAttribute() {
//given
CarDto carDto = new CarDto(
"Morris",
2,
"1980",
new PersonDto( "Bob" ),
new ArrayList<PersonDto>( Arrays.asList( new PersonDto( "Alice" ), new PersonDto( "Bill" ) ) )
);
//when
Car car = CarMapper.INSTANCE.carDtoToCar( carDto );
//when
Car car = CarMapper.INSTANCE.carDtoToCar( carDto );
//then
assertThat( car ).isNotNull();
//then
assertThat( car ).isNotNull();
assertThat( car.getPassengers() ).hasSize( 2 );
assertThat( car.getPassengers().get( 0 ).getName() ).isEqualTo( "Alice" );
assertThat( car.getPassengers().get( 1 ).getName() ).isEqualTo( "Bill" );
}
assertThat( car.getPassengers() ).hasSize( 2 );
assertThat( car.getPassengers().get( 0 ).getName() ).isEqualTo( "Alice" );
assertThat( car.getPassengers().get( 1 ).getName() ).isEqualTo( "Bill" );
}
@Test
public void shouldMapEnumToString() {
//given
Car car = new Car();
car.setCategory( Category.CONVERTIBLE );
//when
CarDto carDto = CarMapper.INSTANCE.carToCarDto( car );
@Test
public void shouldMapEnumToString() {
//given
Car car = new Car();
car.setCategory( Category.CONVERTIBLE );
//when
CarDto carDto = CarMapper.INSTANCE.carToCarDto( car );
//then
assertThat( carDto ).isNotNull();
assertThat( carDto.getCategory() ).isEqualTo( "CONVERTIBLE" );
}
//then
assertThat( carDto ).isNotNull();
assertThat( carDto.getCategory() ).isEqualTo( "CONVERTIBLE" );
}
@Test
public void shouldMapStringToEnum() {
//given
CarDto carDto = new CarDto();
carDto.setCategory( "CONVERTIBLE" );
//when
Car car = CarMapper.INSTANCE.carDtoToCar( carDto );
@Test
public void shouldMapStringToEnum() {
//given
CarDto carDto = new CarDto();
carDto.setCategory( "CONVERTIBLE" );
//when
Car car = CarMapper.INSTANCE.carDtoToCar( carDto );
//then
assertThat( car ).isNotNull();
assertThat( car.getCategory() ).isEqualTo( Category.CONVERTIBLE );
}
//then
assertThat( car ).isNotNull();
assertThat( car.getCategory() ).isEqualTo( Category.CONVERTIBLE );
}
}

View File

@ -29,91 +29,91 @@ import static org.fest.assertions.Assertions.assertThat;
public class ConversionTest extends MapperTestBase {
private DiagnosticCollector<JavaFileObject> diagnostics;
private DiagnosticCollector<JavaFileObject> diagnostics;
public ConversionTest() {
super( "mapstruct.jar" );
}
public ConversionTest() {
super( "mapstruct.jar" );
}
@BeforeMethod
public void generateMapperImplementation() {
diagnostics = new DiagnosticCollector<JavaFileObject>();
File[] sourceFiles = getSourceFiles(
Source.class,
Target.class,
SourceTargetMapper.class
);
@BeforeMethod
public void generateMapperImplementation() {
diagnostics = new DiagnosticCollector<JavaFileObject>();
File[] sourceFiles = getSourceFiles(
Source.class,
Target.class,
SourceTargetMapper.class
);
boolean compilationSuccessful = compile( diagnostics, sourceFiles );
boolean compilationSuccessful = compile( diagnostics, sourceFiles );
assertThat( compilationSuccessful ).describedAs( "Compilation failed: " + diagnostics.getDiagnostics() )
.isTrue();
}
assertThat( compilationSuccessful ).describedAs( "Compilation failed: " + diagnostics.getDiagnostics() )
.isTrue();
}
@Test
public void shouldApplyConversions() {
Source source = new Source();
source.setFoo( 42 );
source.setBar( 23L );
source.setZip( 73 );
@Test
public void shouldApplyConversions() {
Source source = new Source();
source.setFoo( 42 );
source.setBar( 23L );
source.setZip( 73 );
Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source );
Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source );
assertThat( target ).isNotNull();
assertThat( target.getFoo() ).isEqualTo( Long.valueOf( 42 ) );
assertThat( target.getBar() ).isEqualTo( 23 );
assertThat( target.getZip() ).isEqualTo( "73" );
}
assertThat( target ).isNotNull();
assertThat( target.getFoo() ).isEqualTo( Long.valueOf( 42 ) );
assertThat( target.getBar() ).isEqualTo( 23 );
assertThat( target.getZip() ).isEqualTo( "73" );
}
@Test
public void shouldHandleNulls() {
Source source = new Source();
Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source );
@Test
public void shouldHandleNulls() {
Source source = new Source();
Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source );
assertThat( target ).isNotNull();
assertThat( target.getFoo() ).isEqualTo( Long.valueOf( 0 ) );
assertThat( target.getBar() ).isEqualTo( 0 );
assertThat( target.getZip() ).isEqualTo( "0" );
}
assertThat( target ).isNotNull();
assertThat( target.getFoo() ).isEqualTo( Long.valueOf( 0 ) );
assertThat( target.getBar() ).isEqualTo( 0 );
assertThat( target.getZip() ).isEqualTo( "0" );
}
@Test
public void shouldApplyConversionsToMappedProperties() {
Source source = new Source();
source.setQax( 42 );
source.setBaz( 23L );
@Test
public void shouldApplyConversionsToMappedProperties() {
Source source = new Source();
source.setQax( 42 );
source.setBaz( 23L );
Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source );
Target target = SourceTargetMapper.INSTANCE.sourceToTarget( source );
assertThat( target ).isNotNull();
assertThat( target.getBaz() ).isEqualTo( Long.valueOf( 42 ) );
assertThat( target.getQax() ).isEqualTo( 23 );
}
assertThat( target ).isNotNull();
assertThat( target.getBaz() ).isEqualTo( Long.valueOf( 42 ) );
assertThat( target.getQax() ).isEqualTo( 23 );
}
@Test
public void shouldApplyConversionsForReverseMapping() {
Target target = new Target();
target.setFoo( 42L );
target.setBar( 23 );
target.setZip( "73" );
@Test
public void shouldApplyConversionsForReverseMapping() {
Target target = new Target();
target.setFoo( 42L );
target.setBar( 23 );
target.setZip( "73" );
Source source = SourceTargetMapper.INSTANCE.targetToSource( target );
Source source = SourceTargetMapper.INSTANCE.targetToSource( target );
assertThat( source ).isNotNull();
assertThat( source.getFoo() ).isEqualTo( 42 );
assertThat( source.getBar() ).isEqualTo( 23 );
assertThat( source.getZip() ).isEqualTo( 73 );
}
assertThat( source ).isNotNull();
assertThat( source.getFoo() ).isEqualTo( 42 );
assertThat( source.getBar() ).isEqualTo( 23 );
assertThat( source.getZip() ).isEqualTo( 73 );
}
@Test
public void shouldApplyConversionsToMappedPropertiesForReverseMapping() {
Target target = new Target();
target.setQax( 42 );
target.setBaz( 23L );
@Test
public void shouldApplyConversionsToMappedPropertiesForReverseMapping() {
Target target = new Target();
target.setQax( 42 );
target.setBaz( 23L );
Source source = SourceTargetMapper.INSTANCE.targetToSource( target );
Source source = SourceTargetMapper.INSTANCE.targetToSource( target );
assertThat( source ).isNotNull();
assertThat( source.getBaz() ).isEqualTo( 42 );
assertThat( source.getQax() ).isEqualTo( 23 );
}
assertThat( source ).isNotNull();
assertThat( source.getBaz() ).isEqualTo( 42 );
assertThat( source.getQax() ).isEqualTo( 23 );
}
}

View File

@ -36,125 +36,125 @@ import org.testng.annotations.BeforeClass;
public abstract class MapperTestBase {
private JavaCompiler compiler;
private String sourceDir;
private String classOutputDir;
private String sourceOutputDir;
private List<File> classPath;
private List<String> libraries;
private JavaCompiler compiler;
private String sourceDir;
private String classOutputDir;
private String sourceOutputDir;
private List<File> classPath;
private List<String> libraries;
public MapperTestBase(String... libraries) {
this.libraries = Arrays.asList( libraries );
}
public MapperTestBase(String... libraries) {
this.libraries = Arrays.asList( libraries );
}
@BeforeClass
public void setup() throws Exception {
@BeforeClass
public void setup() throws Exception {
compiler = ToolProvider.getSystemJavaCompiler();
compiler = ToolProvider.getSystemJavaCompiler();
String basePath = getBasePath();
String basePath = getBasePath();
sourceDir = basePath + "/src/test/java";
classOutputDir = basePath + "/target/compilation-tests/classes";
sourceOutputDir = basePath + "/target/compilation-tests/generated-sources/mapping";
sourceDir = basePath + "/src/test/java";
classOutputDir = basePath + "/target/compilation-tests/classes";
sourceOutputDir = basePath + "/target/compilation-tests/generated-sources/mapping";
String testDependenciesDir = basePath + "/target/test-dependencies/";
String testDependenciesDir = basePath + "/target/test-dependencies/";
classPath = new ArrayList<File>();
for ( String oneLibrary : libraries ) {
classPath.add( new File( testDependenciesDir, oneLibrary ) );
}
classPath = new ArrayList<File>();
for ( String oneLibrary : libraries ) {
classPath.add( new File( testDependenciesDir, oneLibrary ) );
}
createOutputDirs();
createOutputDirs();
Thread.currentThread().setContextClassLoader(
new URLClassLoader(
new URL[] { new File( classOutputDir ).toURI().toURL() },
Thread.currentThread().getContextClassLoader()
)
);
}
Thread.currentThread().setContextClassLoader(
new URLClassLoader(
new URL[] { new File( classOutputDir ).toURI().toURL() },
Thread.currentThread().getContextClassLoader()
)
);
}
protected File[] getSourceFiles(Class<?>... clazz) {
protected File[] getSourceFiles(Class<?>... clazz) {
File[] sourceFiles = new File[clazz.length];
File[] sourceFiles = new File[clazz.length];
for ( int i = 0; i < clazz.length; i++ ) {
for ( int i = 0; i < clazz.length; i++ ) {
sourceFiles[i] = new File(
sourceDir +
File.separator +
clazz[i].getName().replace( ".", File.separator ) +
".java"
);
}
sourceFiles[i] = new File(
sourceDir +
File.separator +
clazz[i].getName().replace( ".", File.separator ) +
".java"
);
}
return sourceFiles;
}
return sourceFiles;
}
protected boolean compile(DiagnosticCollector<JavaFileObject> diagnostics, File... sourceFiles) {
protected boolean compile(DiagnosticCollector<JavaFileObject> diagnostics, File... sourceFiles) {
StandardJavaFileManager fileManager = compiler.getStandardFileManager( null, null, null );
StandardJavaFileManager fileManager = compiler.getStandardFileManager( null, null, null );
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects( sourceFiles );
Iterable<? extends JavaFileObject> compilationUnits = fileManager.getJavaFileObjects( sourceFiles );
try {
fileManager.setLocation( StandardLocation.CLASS_PATH, classPath );
fileManager.setLocation( StandardLocation.CLASS_OUTPUT, Arrays.asList( new File( classOutputDir ) ) );
fileManager.setLocation( StandardLocation.SOURCE_OUTPUT, Arrays.asList( new File( sourceOutputDir ) ) );
}
catch ( IOException e ) {
throw new RuntimeException( e );
}
try {
fileManager.setLocation( StandardLocation.CLASS_PATH, classPath );
fileManager.setLocation( StandardLocation.CLASS_OUTPUT, Arrays.asList( new File( classOutputDir ) ) );
fileManager.setLocation( StandardLocation.SOURCE_OUTPUT, Arrays.asList( new File( sourceOutputDir ) ) );
}
catch ( IOException e ) {
throw new RuntimeException( e );
}
CompilationTask task = compiler.getTask(
null,
fileManager,
diagnostics,
Collections.<String>emptyList(),
null,
compilationUnits
);
task.setProcessors( Arrays.asList( new MappingProcessor() ) );
CompilationTask task = compiler.getTask(
null,
fileManager,
diagnostics,
Collections.<String>emptyList(),
null,
compilationUnits
);
task.setProcessors( Arrays.asList( new MappingProcessor() ) );
return task.call();
}
return task.call();
}
private String getBasePath() {
private String getBasePath() {
try {
return new File( "." ).getCanonicalPath();
}
catch ( IOException e ) {
throw new RuntimeException( e );
}
}
try {
return new File( "." ).getCanonicalPath();
}
catch ( IOException e ) {
throw new RuntimeException( e );
}
}
private void createOutputDirs() {
private void createOutputDirs() {
File directory = new File( classOutputDir );
deleteDirectory( directory );
directory.mkdirs();
File directory = new File( classOutputDir );
deleteDirectory( directory );
directory.mkdirs();
directory = new File( sourceOutputDir );
deleteDirectory( directory );
directory.mkdirs();
}
directory = new File( sourceOutputDir );
deleteDirectory( directory );
directory.mkdirs();
}
private void deleteDirectory(File path) {
if ( path.exists() ) {
File[] files = path.listFiles();
for ( int i = 0; i < files.length; i++ ) {
if ( files[i].isDirectory() ) {
deleteDirectory( files[i] );
}
else {
files[i].delete();
}
}
}
path.delete();
}
private void deleteDirectory(File path) {
if ( path.exists() ) {
File[] files = path.listFiles();
for ( int i = 0; i < files.length; i++ ) {
if ( files[i].isDirectory() ) {
deleteDirectory( files[i] );
}
else {
files[i].delete();
}
}
}
path.delete();
}
}

View File

@ -17,49 +17,49 @@ package org.mapstruct.ap.test.conversion;
public class Source {
private int foo;
private Long bar;
private int qax;
private Long baz;
private int zip;
private int foo;
private Long bar;
private int qax;
private Long baz;
private int zip;
public int getFoo() {
return foo;
}
public int getFoo() {
return foo;
}
public void setFoo(int foo) {
this.foo = foo;
}
public void setFoo(int foo) {
this.foo = foo;
}
public Long getBar() {
return bar;
}
public Long getBar() {
return bar;
}
public void setBar(Long bar) {
this.bar = bar;
}
public void setBar(Long bar) {
this.bar = bar;
}
public int getQax() {
return qax;
}
public int getQax() {
return qax;
}
public void setQax(int qax) {
this.qax = qax;
}
public void setQax(int qax) {
this.qax = qax;
}
public Long getBaz() {
return baz;
}
public Long getBaz() {
return baz;
}
public void setBaz(Long baz) {
this.baz = baz;
}
public void setBaz(Long baz) {
this.baz = baz;
}
public int getZip() {
return zip;
}
public int getZip() {
return zip;
}
public void setZip(int zip) {
this.zip = zip;
}
public void setZip(int zip) {
this.zip = zip;
}
}

View File

@ -23,13 +23,13 @@ import org.mapstruct.Mappings;
@Mapper
public interface SourceTargetMapper {
public static SourceTargetMapper INSTANCE = Mappers.getMapper( SourceTargetMapper.class );
public static SourceTargetMapper INSTANCE = Mappers.getMapper( SourceTargetMapper.class );
@Mappings({
@Mapping(source = "qax", target = "baz"),
@Mapping(source = "baz", target = "qax")
})
Target sourceToTarget(Source source);
@Mappings({
@Mapping(source = "qax", target = "baz"),
@Mapping(source = "baz", target = "qax")
})
Target sourceToTarget(Source source);
Source targetToSource(Target target);
Source targetToSource(Target target);
}

View File

@ -17,49 +17,49 @@ package org.mapstruct.ap.test.conversion;
public class Target {
private Long foo;
private int bar;
private Long baz;
private int qax;
private String zip;
private Long foo;
private int bar;
private Long baz;
private int qax;
private String zip;
public Long getFoo() {
return foo;
}
public Long getFoo() {
return foo;
}
public void setFoo(Long foo) {
this.foo = foo;
}
public void setFoo(Long foo) {
this.foo = foo;
}
public int getBar() {
return bar;
}
public int getBar() {
return bar;
}
public void setBar(int bar) {
this.bar = bar;
}
public void setBar(int bar) {
this.bar = bar;
}
public Long getBaz() {
return baz;
}
public Long getBaz() {
return baz;
}
public void setBaz(Long baz) {
this.baz = baz;
}
public void setBaz(Long baz) {
this.baz = baz;
}
public int getQax() {
return qax;
}
public int getQax() {
return qax;
}
public void setQax(int qax) {
this.qax = qax;
}
public void setQax(int qax) {
this.qax = qax;
}
public String getZip() {
return zip;
}
public String getZip() {
return zip;
}
public void setZip(String zip) {
this.zip = zip;
}
public void setZip(String zip) {
this.zip = zip;
}
}

View File

@ -20,78 +20,78 @@ import java.util.Date;
public class Car {
private String make;
private int numberOfSeats;
private Date manufacturingDate;
private Person driver;
private ArrayList<Person> passengers;
private int price;
private Category category;
private String make;
private int numberOfSeats;
private Date manufacturingDate;
private Person driver;
private ArrayList<Person> passengers;
private int price;
private Category category;
public Car() {
}
public Car() {
}
public Car(String make, int numberOfSeats, Date manufacturingDate, Person driver, ArrayList<Person> passengers) {
this.make = make;
this.numberOfSeats = numberOfSeats;
this.manufacturingDate = manufacturingDate;
this.driver = driver;
this.passengers = passengers;
}
public Car(String make, int numberOfSeats, Date manufacturingDate, Person driver, ArrayList<Person> passengers) {
this.make = make;
this.numberOfSeats = numberOfSeats;
this.manufacturingDate = manufacturingDate;
this.driver = driver;
this.passengers = passengers;
}
public String getMake() {
return make;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public void setMake(String make) {
this.make = make;
}
public int getNumberOfSeats() {
return numberOfSeats;
}
public int getNumberOfSeats() {
return numberOfSeats;
}
public void setNumberOfSeats(int numberOfSeats) {
this.numberOfSeats = numberOfSeats;
}
public void setNumberOfSeats(int numberOfSeats) {
this.numberOfSeats = numberOfSeats;
}
public Date getManufacturingDate() {
return manufacturingDate;
}
public Date getManufacturingDate() {
return manufacturingDate;
}
public void setManufacturingDate(Date manufacturingDate) {
this.manufacturingDate = manufacturingDate;
}
public void setManufacturingDate(Date manufacturingDate) {
this.manufacturingDate = manufacturingDate;
}
public Person getDriver() {
return driver;
}
public Person getDriver() {
return driver;
}
public void setDriver(Person driver) {
this.driver = driver;
}
public void setDriver(Person driver) {
this.driver = driver;
}
public ArrayList<Person> getPassengers() {
return passengers;
}
public ArrayList<Person> getPassengers() {
return passengers;
}
public void setPassengers(ArrayList<Person> passengers) {
this.passengers = passengers;
}
public void setPassengers(ArrayList<Person> passengers) {
this.passengers = passengers;
}
public int getPrice() {
return price;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public void setPrice(int price) {
this.price = price;
}
public Category getCategory() {
return category;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
public void setCategory(Category category) {
this.category = category;
}
}

View File

@ -19,78 +19,78 @@ import java.util.ArrayList;
public class CarDto {
private String make;
private int seatCount;
private String manufacturingYear;
private PersonDto driver;
private ArrayList<PersonDto> passengers;
private Long price;
private String category;
private String make;
private int seatCount;
private String manufacturingYear;
private PersonDto driver;
private ArrayList<PersonDto> passengers;
private Long price;
private String category;
public CarDto() {
}
public CarDto() {
}
public CarDto(String make, int seatCount, String manufacturingYear, PersonDto driver, ArrayList<PersonDto> passengers) {
this.make = make;
this.seatCount = seatCount;
this.manufacturingYear = manufacturingYear;
this.driver = driver;
this.passengers = passengers;
}
public CarDto(String make, int seatCount, String manufacturingYear, PersonDto driver, ArrayList<PersonDto> passengers) {
this.make = make;
this.seatCount = seatCount;
this.manufacturingYear = manufacturingYear;
this.driver = driver;
this.passengers = passengers;
}
public String getMake() {
return make;
}
public String getMake() {
return make;
}
public void setMake(String make) {
this.make = make;
}
public void setMake(String make) {
this.make = make;
}
public int getSeatCount() {
return seatCount;
}
public int getSeatCount() {
return seatCount;
}
public void setSeatCount(int seatCount) {
this.seatCount = seatCount;
}
public void setSeatCount(int seatCount) {
this.seatCount = seatCount;
}
public String getManufacturingYear() {
return manufacturingYear;
}
public String getManufacturingYear() {
return manufacturingYear;
}
public void setManufacturingYear(String manufacturingYear) {
this.manufacturingYear = manufacturingYear;
}
public void setManufacturingYear(String manufacturingYear) {
this.manufacturingYear = manufacturingYear;
}
public PersonDto getDriver() {
return driver;
}
public PersonDto getDriver() {
return driver;
}
public void setDriver(PersonDto driver) {
this.driver = driver;
}
public void setDriver(PersonDto driver) {
this.driver = driver;
}
public ArrayList<PersonDto> getPassengers() {
return passengers;
}
public ArrayList<PersonDto> getPassengers() {
return passengers;
}
public void setPassengers(ArrayList<PersonDto> passengers) {
this.passengers = passengers;
}
public void setPassengers(ArrayList<PersonDto> passengers) {
this.passengers = passengers;
}
public Long getPrice() {
return price;
}
public Long getPrice() {
return price;
}
public void setPrice(Long price) {
this.price = price;
}
public void setPrice(Long price) {
this.price = price;
}
public String getCategory() {
return category;
}
public String getCategory() {
return category;
}
public void setCategory(String category) {
this.category = category;
}
public void setCategory(String category) {
this.category = category;
}
}

View File

@ -25,25 +25,25 @@ import org.mapstruct.Mappings;
@Mapper(uses = DateMapper.class)
public interface CarMapper {
CarMapper INSTANCE = Mappers.getMapper( CarMapper.class );
CarMapper INSTANCE = Mappers.getMapper( CarMapper.class );
@Mappings({
@Mapping(source = "numberOfSeats", target = "seatCount"),
@Mapping(source = "manufacturingDate", target = "manufacturingYear")
})
CarDto carToCarDto(Car car);
@Mappings({
@Mapping(source = "numberOfSeats", target = "seatCount"),
@Mapping(source = "manufacturingDate", target = "manufacturingYear")
})
CarDto carToCarDto(Car car);
Car carDtoToCar(CarDto carDto);
Car carDtoToCar(CarDto carDto);
ArrayList<CarDto> carsToCarDtos(ArrayList<Car> cars);
ArrayList<CarDto> carsToCarDtos(ArrayList<Car> cars);
ArrayList<Car> carDtosToCars(ArrayList<CarDto> carDtos);
ArrayList<Car> carDtosToCars(ArrayList<CarDto> carDtos);
PersonDto personToPersonDto(Person person);
PersonDto personToPersonDto(Person person);
Person personDtoToPerson(PersonDto personDto);
Person personDtoToPerson(PersonDto personDto);
ArrayList<PersonDto> personsToPersonDtos(ArrayList<Person> persons);
ArrayList<PersonDto> personsToPersonDtos(ArrayList<Person> persons);
ArrayList<Person> personDtosToPersons(ArrayList<PersonDto> personDtos);
ArrayList<Person> personDtosToPersons(ArrayList<PersonDto> personDtos);
}

View File

@ -16,5 +16,5 @@
package org.mapstruct.ap.test.model;
public enum Category {
SEDAN, CONVERTIBLE, TRUCK;
SEDAN, CONVERTIBLE, TRUCK;
}

View File

@ -21,16 +21,16 @@ import java.util.Date;
public class DateMapper {
public String asString(Date date) {
return date != null ? new SimpleDateFormat( "yyyy" ).format( date ) : null;
}
public String asString(Date date) {
return date != null ? new SimpleDateFormat( "yyyy" ).format( date ) : null;
}
public Date asDate(String date) {
try {
return date != null ? new SimpleDateFormat( "yyyy" ).parse( date ) : null;
}
catch ( ParseException e ) {
throw new RuntimeException( e );
}
}
public Date asDate(String date) {
try {
return date != null ? new SimpleDateFormat( "yyyy" ).parse( date ) : null;
}
catch ( ParseException e ) {
throw new RuntimeException( e );
}
}
}

View File

@ -17,20 +17,20 @@ package org.mapstruct.ap.test.model;
public class Person {
private String name;
private String name;
public Person() {
}
public Person() {
}
public Person(String name) {
this.name = name;
}
public Person(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
}

View File

@ -17,20 +17,20 @@ package org.mapstruct.ap.test.model;
public class PersonDto {
private String name;
private String name;
public PersonDto() {
}
public PersonDto() {
}
public PersonDto(String name) {
this.name = name;
}
public PersonDto(String name) {
this.name = name;
}
public String getName() {
return name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public void setName(String name) {
this.name = name;
}
}