#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. 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"> 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> <modelVersion>4.0.0</modelVersion>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -16,8 +16,9 @@
limitations under the License. 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"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> 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> <modelVersion>4.0.0</modelVersion>
<parent> <parent>

View File

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

View File

@ -23,13 +23,13 @@ import org.mapstruct.Mappings;
@Mapper @Mapper
public interface SourceTargetMapper { public interface SourceTargetMapper {
public static SourceTargetMapper INSTANCE = Mappers.getMapper( SourceTargetMapper.class ); public static SourceTargetMapper INSTANCE = Mappers.getMapper( SourceTargetMapper.class );
@Mappings({ @Mappings({
@Mapping(source = "qax", target = "baz"), @Mapping(source = "qax", target = "baz"),
@Mapping(source = "baz", target = "qax") @Mapping(source = "baz", target = "qax")
}) })
Target sourceToTarget(Source source); 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 { public class Target {
private Long foo; private Long foo;
private int bar; private int bar;
private Long baz; private Long baz;
private int qax; private int qax;
private String zip; private String zip;
public Long getFoo() { public Long getFoo() {
return foo; return foo;
} }
public void setFoo(Long foo) { public void setFoo(Long foo) {
this.foo = foo; this.foo = foo;
} }
public int getBar() { public int getBar() {
return bar; return bar;
} }
public void setBar(int bar) { public void setBar(int bar) {
this.bar = bar; this.bar = bar;
} }
public Long getBaz() { public Long getBaz() {
return baz; return baz;
} }
public void setBaz(Long baz) { public void setBaz(Long baz) {
this.baz = baz; this.baz = baz;
} }
public int getQax() { public int getQax() {
return qax; return qax;
} }
public void setQax(int qax) { public void setQax(int qax) {
this.qax = qax; this.qax = qax;
} }
public String getZip() { public String getZip() {
return zip; return zip;
} }
public void setZip(String zip) { public void setZip(String zip) {
this.zip = zip; this.zip = zip;
} }
} }

View File

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

View File

@ -16,7 +16,8 @@
limitations under the License. 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"> 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> <modelVersion>4.0.0</modelVersion>

View File

@ -16,7 +16,8 @@
limitations under the License. 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"> 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> <modelVersion>4.0.0</modelVersion>

View File

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

View File

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

View File

@ -33,45 +33,45 @@ import org.mapstruct.Mappings;
@SupportedAnnotationTypes("org.mapstruct.Mapper") @SupportedAnnotationTypes("org.mapstruct.Mapper")
@GeneratePrisms({ @GeneratePrisms({
@GeneratePrism(value = Mapper.class), @GeneratePrism(value = Mapper.class),
@GeneratePrism(value = Mapping.class), @GeneratePrism(value = Mapping.class),
@GeneratePrism(value = Mappings.class) @GeneratePrism(value = Mappings.class)
}) })
public class MappingProcessor extends AbstractProcessor { public class MappingProcessor extends AbstractProcessor {
/** /**
* Whether this processor claims all processed annotations exclusively or not. * Whether this processor claims all processed annotations exclusively or not.
*/ */
private static final boolean ANNOTATIONS_CLAIMED_EXCLUSIVELY = false; private static final boolean ANNOTATIONS_CLAIMED_EXCLUSIVELY = false;
@Override @Override
public synchronized void init(ProcessingEnvironment processingEnv) { public synchronized void init(ProcessingEnvironment processingEnv) {
super.init( processingEnv ); super.init( processingEnv );
} }
@Override @Override
public SourceVersion getSupportedSourceVersion() { public SourceVersion getSupportedSourceVersion() {
return SourceVersion.latestSupported(); return SourceVersion.latestSupported();
} }
@Override @Override
public boolean process( public boolean process(
final Set<? extends TypeElement> annotations, final Set<? extends TypeElement> annotations,
final RoundEnvironment roundEnvironment) { 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 //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. //project. Let the compiler deal with that and print an appropriate error.
if ( oneAnnotation.getKind() != ElementKind.ANNOTATION_TYPE ) { if ( oneAnnotation.getKind() != ElementKind.ANNOTATION_TYPE ) {
continue; continue;
} }
for ( Element oneAnnotatedElement : roundEnvironment.getElementsAnnotatedWith( oneAnnotation ) ) { for ( Element oneAnnotatedElement : roundEnvironment.getElementsAnnotatedWith( oneAnnotation ) ) {
oneAnnotatedElement.accept( new MapperGenerationVisitor( processingEnv ), null ); 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 { 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 { public class Conversions {
private TypeUtil typeUtil; private TypeUtil typeUtil;
private final Map<Key, Conversion> conversions = new HashMap<Conversions.Key, Conversion>(); private final Map<Key, Conversion> conversions = new HashMap<Conversions.Key, Conversion>();
private final DeclaredType enumType; private final DeclaredType enumType;
private final DeclaredType stringType; private final DeclaredType stringType;
public Conversions(Elements elementUtils, Types typeUtils, TypeUtil typeUtil) { public Conversions(Elements elementUtils, Types typeUtils, TypeUtil typeUtil) {
this.typeUtil = typeUtil; this.typeUtil = typeUtil;
this.enumType = typeUtils.getDeclaredType( elementUtils.getTypeElement( Enum.class.getCanonicalName() ) ); this.enumType = typeUtils.getDeclaredType( elementUtils.getTypeElement( Enum.class.getCanonicalName() ) );
this.stringType = typeUtils.getDeclaredType( elementUtils.getTypeElement( String.class.getCanonicalName() ) ); this.stringType = typeUtils.getDeclaredType( elementUtils.getTypeElement( String.class.getCanonicalName() ) );
register( int.class, Long.class, new IntLongConversion() ); register( int.class, Long.class, new IntLongConversion() );
register( int.class, String.class, new IntStringConversion() ); register( int.class, String.class, new IntStringConversion() );
register( Enum.class, String.class, new EnumStringConversion() ); register( Enum.class, String.class, new EnumStringConversion() );
} }
private void register(Class<?> sourceType, Class<?> targetType, Conversion conversion) { private void register(Class<?> sourceType, Class<?> targetType, Conversion conversion) {
conversions.put( Key.forClasses( sourceType, targetType ), conversion ); conversions.put( Key.forClasses( sourceType, targetType ), conversion );
conversions.put( Key.forClasses( targetType, sourceType ), reverse( conversion ) ); conversions.put( Key.forClasses( targetType, sourceType ), reverse( conversion ) );
} }
public Conversion getConversion(Type sourceType, Type targetType) { public Conversion getConversion(Type sourceType, Type targetType) {
if ( sourceType.isEnumType() && targetType.equals( typeUtil.getType( stringType ) ) ) { if ( sourceType.isEnumType() && targetType.equals( typeUtil.getType( stringType ) ) ) {
sourceType = typeUtil.getType( enumType ); sourceType = typeUtil.getType( enumType );
} }
return conversions.get( new Key( sourceType, targetType ) ); return conversions.get( new Key( sourceType, targetType ) );
} }
private static class Key { private static class Key {
private final Type sourceType; private final Type sourceType;
private final Type targetType; private final Type targetType;
private static Key forClasses(Class<?> sourceType, Class<?> targetType) { private static Key forClasses(Class<?> sourceType, Class<?> targetType) {
return new Key( Type.forClass( sourceType ), Type.forClass( targetType ) ); return new Key( Type.forClass( sourceType ), Type.forClass( targetType ) );
} }
private Key(Type sourceType, Type targetType) { private Key(Type sourceType, Type targetType) {
this.sourceType = sourceType; this.sourceType = sourceType;
this.targetType = targetType; this.targetType = targetType;
} }
@Override @Override
public String toString() { public String toString() {
return "Key [sourceType=" + sourceType + ", targetType=" return "Key [sourceType=" + sourceType + ", targetType="
+ targetType + "]"; + targetType + "]";
} }
@Override @Override
public int hashCode() { public int hashCode() {
final int prime = 31; final int prime = 31;
int result = 1; int result = 1;
result = prime * result result = prime * result
+ ( ( sourceType == null ) ? 0 : sourceType.hashCode() ); + ( ( sourceType == null ) ? 0 : sourceType.hashCode() );
result = prime * result result = prime * result
+ ( ( targetType == null ) ? 0 : targetType.hashCode() ); + ( ( targetType == null ) ? 0 : targetType.hashCode() );
return result; return result;
} }
@Override @Override
public boolean equals(Object obj) { public boolean equals(Object obj) {
if ( this == obj ) { if ( this == obj ) {
return true; return true;
} }
if ( obj == null ) { if ( obj == null ) {
return false; return false;
} }
if ( getClass() != obj.getClass() ) { if ( getClass() != obj.getClass() ) {
return false; return false;
} }
Key other = (Key) obj; Key other = (Key) obj;
if ( sourceType == null ) { if ( sourceType == null ) {
if ( other.sourceType != null ) { if ( other.sourceType != null ) {
return false; return false;
} }
} }
else if ( !sourceType.equals( other.sourceType ) ) { else if ( !sourceType.equals( other.sourceType ) ) {
return false; return false;
} }
if ( targetType == null ) { if ( targetType == null ) {
if ( other.targetType != null ) { if ( other.targetType != null ) {
return false; return false;
} }
} }
else if ( !targetType.equals( other.targetType ) ) { else if ( !targetType.equals( other.targetType ) ) {
return false; return false;
} }
return true; return true;
} }
} }
} }

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@ -23,13 +23,13 @@ import org.mapstruct.Mappings;
@Mapper @Mapper
public interface SourceTargetMapper { public interface SourceTargetMapper {
public static SourceTargetMapper INSTANCE = Mappers.getMapper( SourceTargetMapper.class ); public static SourceTargetMapper INSTANCE = Mappers.getMapper( SourceTargetMapper.class );
@Mappings({ @Mappings({
@Mapping(source = "qax", target = "baz"), @Mapping(source = "qax", target = "baz"),
@Mapping(source = "baz", target = "qax") @Mapping(source = "baz", target = "qax")
}) })
Target sourceToTarget(Source source); 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 { public class Target {
private Long foo; private Long foo;
private int bar; private int bar;
private Long baz; private Long baz;
private int qax; private int qax;
private String zip; private String zip;
public Long getFoo() { public Long getFoo() {
return foo; return foo;
} }
public void setFoo(Long foo) { public void setFoo(Long foo) {
this.foo = foo; this.foo = foo;
} }
public int getBar() { public int getBar() {
return bar; return bar;
} }
public void setBar(int bar) { public void setBar(int bar) {
this.bar = bar; this.bar = bar;
} }
public Long getBaz() { public Long getBaz() {
return baz; return baz;
} }
public void setBaz(Long baz) { public void setBaz(Long baz) {
this.baz = baz; this.baz = baz;
} }
public int getQax() { public int getQax() {
return qax; return qax;
} }
public void setQax(int qax) { public void setQax(int qax) {
this.qax = qax; this.qax = qax;
} }
public String getZip() { public String getZip() {
return zip; return zip;
} }
public void setZip(String zip) { public void setZip(String zip) {
this.zip = zip; this.zip = zip;
} }
} }

View File

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

View File

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

View File

@ -25,25 +25,25 @@ import org.mapstruct.Mappings;
@Mapper(uses = DateMapper.class) @Mapper(uses = DateMapper.class)
public interface CarMapper { public interface CarMapper {
CarMapper INSTANCE = Mappers.getMapper( CarMapper.class ); CarMapper INSTANCE = Mappers.getMapper( CarMapper.class );
@Mappings({ @Mappings({
@Mapping(source = "numberOfSeats", target = "seatCount"), @Mapping(source = "numberOfSeats", target = "seatCount"),
@Mapping(source = "manufacturingDate", target = "manufacturingYear") @Mapping(source = "manufacturingDate", target = "manufacturingYear")
}) })
CarDto carToCarDto(Car car); 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; package org.mapstruct.ap.test.model;
public enum Category { public enum Category {
SEDAN, CONVERTIBLE, TRUCK; SEDAN, CONVERTIBLE, TRUCK;
} }

View File

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

View File

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

View File

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