BAEL-3097 init for mapstruct custom mapping method

This commit is contained in:
anilkivilcim.eray 2019-08-18 20:02:31 +03:00
parent fc822dec7d
commit 0b7ceebb66
5 changed files with 91 additions and 0 deletions

View File

@ -0,0 +1,11 @@
package com.baeldung.dto;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class UrlDTO {
private String url;
private String subUrl;
}

View File

@ -0,0 +1,11 @@
package com.baeldung.entity;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class UrlObject {
private String url;
private String subUrl;
}

View File

@ -0,0 +1,13 @@
package com.baeldung.mapper;
import org.mapstruct.Qualifier;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Qualifier
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.CLASS)
public @interface SuffixRemover {}

View File

@ -0,0 +1,34 @@
package com.baeldung.mapper;
import com.baeldung.dto.UrlDTO;
import com.baeldung.entity.UrlObject;
import org.mapstruct.Mapper;
import org.mapstruct.Mapping;
import org.mapstruct.Named;
import org.mapstruct.factory.Mappers;
import java.net.URI;
import java.net.URISyntaxException;
@Mapper
public interface UrlMapper {
UrlMapper INSTANCE = Mappers.getMapper(UrlMapper.class);
@Mapping(source = "subUrl", target = "subUrl", qualifiedByName = "protocolRemover")
@Mapping(source = "url", target = "url", qualifiedBy = SuffixRemover.class)
public UrlObject urlObjectDomainMapper(UrlDTO urlDTO);
@Named("protocolRemover")
public static String protocolRemoverWithCustomMethod(String domain) throws URISyntaxException {
URI uri = new URI(domain);
return uri.getHost();
}
@SuffixRemover
public static String protocolRemoverMethod(String domain) throws URISyntaxException {
URI uri = new URI(domain);
return uri.getHost();
}
}

View File

@ -0,0 +1,22 @@
package com.baeldung.mapper;
import com.baeldung.dto.UrlDTO;
import com.baeldung.entity.UrlObject;
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class UrlMapperTest {
@Test
public void givenDomains_whenCallDomainMapper_thenReturnDomainsWithoutProtocols() {
UrlDTO dto = new UrlDTO();
dto.setUrl("http://www.baeldung.com");
dto.setSubUrl("https://www.baeldung.com");
UrlObject urlObject = UrlMapper.INSTANCE.urlObjectDomainMapper(dto);
assertEquals(urlObject.getUrl(), "www.baeldung.com");
assertEquals(urlObject.getSubUrl(), "www.baeldung.com");
}
}