Skip to content

Instantly share code, notes, and snippets.

@deyvisonborges
Created March 28, 2024 19:56
Show Gist options
  • Save deyvisonborges/08a69809d84f21cfd7d03daadd7d6313 to your computer and use it in GitHub Desktop.
Save deyvisonborges/08a69809d84f21cfd7d03daadd7d6313 to your computer and use it in GitHub Desktop.
/**
* Converter for converting a string CodeValue on the DTO into a Code object with type ITEM_TYPE_CODE
*/
Converter<String, Code> itemTypeCodeConverter = new Converter<String, Code>() {
public Code convert(MappingContext<String, Code> context) {
Code itemTypeCode = null;
for (Code code : ModelMapperExampleApplication.storedCodes) {
if (code.getCodeType().equals(ModelMapperExampleApplication.ITEM_TYPE_CODE)
&& code.getCodeValue().equals(context.getSource())) {
itemTypeCode = code;
break;
}
}
return itemTypeCode;
}
};
/**
* Converter for converting a string CodeValue on the DTO into a Code object with type LOCATION_CODE
*/
Converter<String, Code> locationCodeConverter = new Converter<String, Code>() {
public Code convert(MappingContext<String, Code> context) {
Code locationCode = null;
for (Code code : ModelMapperExampleApplication.storedCodes) {
if (code.getCodeType().equals(ModelMapperExampleApplication.LOCATION_CODE)
&& code.getCodeValue().equals(context.getSource())) {
locationCode = code;
break;
}
}
return locationCode;
}
};
/**
* Mapping for converting String Code Keys from ItemDTO to Code objects.
* To use:
* modelMapper.addMappings(itemMap);
*
*/
PropertyMap<ItemDTO, Item> itemMap = new PropertyMap<ItemDTO, Item>() {
protected void configure() {
using(itemTypeCodeConverter).map(source.getItemType()).setItemTypeCode(null);
using(locationCodeConverter).map(source.getLocation()).setLocationCode(null);
}
};
@Autowired
public ItemController(ModelMapper modelMapper) {
this.modelMapper = modelMapper;
this.modelMapper.addMappings(itemMap);
}
**
* Converter for converting a into a String CodeValue on the DTO
*/
Converter<Code, String> codeToStringConverter = new Converter<Code, String>() {
public String convert(MappingContext<Code, String> context) {
return (context.getSource()!= null? context.getSource().getCodeValue():"");
}
};
/**
* Converter for converting a into a String Short Description on the DTO
*/
Converter<Code, String> codeToStringDescConverter = new Converter<Code, String>() {
public String convert(MappingContext<Code, String> context) {
return (context.getSource()!= null? context.getSource().getShortDescription():"");
}
};
/**
* Mapping for converting Code objects into String Code Keys on ItemDto.
* To use:
* modelMapper.addMappings(itemDtoMap);
*
*/
PropertyMap<Item, ItemDTO> itemDtoMap = new PropertyMap<Item, ItemDTO>() {
protected void configure() {
using(codeToStringConverter).map(source.getItemTypeCode()).setItemType(null);
using(codeToStringConverter).map(source.getLocationCode()).setLocation(null);
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment