MapStruct QualifiedByName with multiple parameters - java

I have come across a situation where my mapping method has 3 parameters, and all the three are being used in deriving one of the properties of the target type.
I have created a default mapping method in the interface keeping the logic for deriving the property, now for calling this method, I could use an expression = "java( /*method call here*/ )" in the #Mapping annotation.
Is there any way to do this with any of the mapstruct annotation like #qualifiedByName, I tried commenting the annotation having expression property and used qualifiedByName, but it doesn't work :
#Mapper
public interface OneMapper {
#Mapping(target="id", source="one.id")
//#Mapping(target="qualified",expression = "java( checkQualified (one, projId, code) )")
#Mapping(target="qualified",qualifiedByName="checkQualifiedNamed")
OneDto createOne (One one, Integer projId, Integer val, String code);
#Named("checkQualifiedNamed")
default Boolean checkQualified (One one, Integer projId, Integer val, String code) {
if(one.getProjectId() == projId && one.getVal() == val && one.getCode().equalsIgnoreCase(code)) {
return Boolean.TRUE;
}
return Boolean.FALSE;
}
}

Currently MapStruct does not support mapping methods with multiple source properties.
However, in your case you can use the #Context from 1.2.0. From what I understand the projId and the code are there just as helper of the mapping, and they are not used to map target properties from.
So you can do something like (It should work in theory):
#Mapper
public interface OneMapper {
#Mapping(target="id", source="one.id")
#Mapping(target="qualified", qualifiedByName="checkQualifiedNamed")
OneDto createOne (One one, #Context Integer projId, #Context String code);
#Named("checkQualifiedNamed")
default Boolean checkQualified (One one, #Context Integer projId, #Context String code) {
if(one.getProjectId() == projId && one.getCode().equalsIgnoreCase(code)) {
return Boolean.TRUE;
}
return Boolean.FALSE;
}
}
Another alternative would be to extract all those properties into a separate class and pass that along (this would allow for multiple parameters of the same type).
The class would look like:
public class Filter {
private final Integer projId;
private final Integer val;
private final String code;
public Filter (Integer projId, Integer val, String code) {
this.projId = projId;
this.val = val;
this.code = code;
}
//getters
}
Your mapper will then look like:
#Mapper
public interface OneMapper {
#Mapping(target="id", source="one.id")
#Mapping(target="qualified", qualifiedByName="checkQualifiedNamed")
OneDto createOne (One one, #Context Filter filter);
#Named("checkQualifiedNamed")
default Boolean checkQualified (One one, #Context Filter filter) {
if(one.getProjectId() == filter.getProjId() && one.getVal() == filter.getVal() && one.getCode().equalsIgnoreCase(filter.getCode())) {
return Boolean.TRUE;
}
return Boolean.FALSE;
}
}
You can then call the mapper like: mapper.createOne(one, new Filter(projId, val, code));

Since version 1.2 it is supported:
http://mapstruct.org/documentation/stable/reference/html/#mappings-with-several-source-parameters
For example like this:
#Mapping(source = "person.description", target = "description")
#Mapping(source = "address.houseNo", target = "houseNumber")
DeliveryAddressDto personAndAddressToDeliveryAddressDto(Person person, Address address);
UPDATE
Since Mapstruct allows to map multiple source arguments into a single target, I would advise to extract the checkQualified method from the mapper and instead compute the outcome beforehand and invoke the mapper with the result of the checkQualified method. Mapstruct is a mapping library, and does not excel in performing arbitrary logic. It's not impossible, but personally, I don't see the value it adds in your particular case.
With the logic extracted your mapper could look like this:
#Mapper
public interface OneMapper {
OneDto toOneDto(One one, Boolean qualified);
}
The mapper can be used like this:
One one = new One(1, 10, 100, "one");
boolean qualified = checkQualified(one, 10, 100, "one");
boolean notQualified = checkQualified(one, 10, 100, "two");
OneDto oneDto = mapper.toOneDto(one, isQualified);
For a full example, see: https://github.com/phazebroek/so-mapstruct/blob/master/src/main/java/nl/phazebroek/so/MapStructDemo.java

If you need to calculate a single target field based on multiple source fields from the same source object, you can pass the full source object to the custom mapper function instead of individual fields:
Example Entity:
#Entity
#Data
public class User {
private String firstName;
private String lastName;
}
Example DTO:
public class UserDto {
private String fullName;
}
... and the mapper... Instead of passing a single source (firstName):
#Mapper
public abstract class UserMapper {
#Mapping(source = "firstName", target = "fullName", qualifiedByName = "nameTofullName")
public abstract UserDto userEntityToUserDto(UserEntity userEntity);
#Named("nameToFullName")
public String nameToFullName(String firstName) {
return String.format("%s HOW DO I GET THE LAST NAME HERE?", firstName);
}
... pass the full entity object (userEntity) as the source:
#Mapper
public abstract class UserMapper {
#Mapping(source = "userEntity", target = "fullName", qualifiedByName = "nameToFullName")
public abstract UserDto userEntityToUserDto(UserEntity userEntity);
#Named("nameToFullName")
public String nameToOwner(UserEntity userEntity) {
return String.format("%s %s", userEntity.getFirstName(), userEntity.getLastName());
}

You can create a default method which calls internally mapstruct method with additional context params.in this way, you can obtain all parameters in 'qualifiedByName' part
#Mapper
public interface OneMapper {
default OneDto createOne(One one, Integer projId, Integer val, String code) {
return createOneWithContext(one,porjId,val,code
one,porjId,val,code //as context params
);
}
#Mapping(target="id", source="one.id")
#Mapping(target="qualified",source="one",qualifiedByName="checkQualifiedNamed")
OneDto createOneWithContext (One one, Integer projId, Integer val, String code
#Context One oneAsContext,
#Context Integer projIdAsContext,
#Context Integer valAsContext,
#Context String codeAsContext
);
#Named("checkQualifiedNamed")
default Boolean checkQualified (One one, #Context Integer projId, #Context Integer val, #Context String code) {
if(one.getProjectId() == projId && one.getVal() == val && one.getCode().equalsIgnoreCase(code)) {
return Boolean.TRUE;
}
return Boolean.FALSE;
}
}
```

Related

How to apply a recipe on a specific method parameter

In my recipe I select the method parameters which have both the NotNull and RequestParam annotations and I want to apply the OpenRewrite recipe AddOrUpdateAnnotationAttribute on these method parameters to set the required attribute to true of the RequestParam annotation.
I'm struggling how to apply a recipe on a specific piece of code, not on the complete Java class. Does somebody has an example?
An example of the source code before applying my recipe:
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.constraints.NotNull;
class ControllerClass {
public String sayHello (
#NotNull #RequestParam(value = "name") String name,
#RequestParam(value = "lang") String lang
) {
return "Hello";
}
}
The expected source code after applying my recipe:
import org.springframework.web.bind.annotation.RequestParam;
import javax.validation.constraints.NotNull;
class ControllerClass {
public String sayHello (
#NotNull #RequestParam(required = true, value = "name") String name,
#RequestParam(value = "lang") String lang
) {
return "Hello";
}
}
Only the first parameter name needs to be adopted as the second parameter has no NotNull annotation.
My (simplified) recipe:
public class MandatoryRequestParameter extends Recipe {
#Override
public #NotNull String getDisplayName() {
return "Make RequestParam mandatory";
}
#Override
protected #NotNull JavaIsoVisitor<ExecutionContext> getVisitor() {
return new MandatoryRequestParameterVisitor();
}
public class MandatoryRequestParameterVisitor extends JavaIsoVisitor<ExecutionContext> {
#Override
public #NotNull J.MethodDeclaration visitMethodDeclaration(#NotNull J.MethodDeclaration methodDeclaration, #NotNull ExecutionContext executionContext) {
J.MethodDeclaration methodDecl = super.visitMethodDeclaration(methodDeclaration, executionContext);
return methodDeclaration.withParameters(ListUtils.map(methodDecl.getParameters(), (i, p) -> makeRequestParamMandatory(p, executionContext)));
}
private Statement makeRequestParamMandatory(Statement statement, ExecutionContext executionContext) {
if (!(statement instanceof J.VariableDeclarations methodParameterDeclaration) || methodParameterDeclaration.getLeadingAnnotations().size() < 2) {
return statement;
}
AddOrUpdateAnnotationAttribute addOrUpdateAnnotationAttribute = new AddOrUpdateAnnotationAttribute(
"org.springframework.web.bind.annotation.RequestParam", "required", "true", false
);
return (Statement) methodParameterDeclaration.acceptJava(addOrUpdateAnnotationAttribute.getVisitor(), executionContext);
}
}
}
When I execute my recipe, I got following error so my implementation is not the correct way of applying a recipe.
org.openrewrite.UncaughtVisitorException: java.lang.IllegalStateException: Expected to find a matching parent for Cursor{Annotation-\>root}
at org.openrewrite.TreeVisitor.visit(TreeVisitor.java:253)
at org.openrewrite.TreeVisitor.visit(TreeVisitor.java:145)
at org.openrewrite.java.JavaTemplate.withTemplate(JavaTemplate.java:520)
at org.openrewrite.java.JavaTemplate.withTemplate(JavaTemplate.java:42)
at org.openrewrite.java.tree.J.withTemplate(J.java:87)
at org.openrewrite.java.AddOrUpdateAnnotationAttribute$1.visitAnnotation(AddOrUpdateAnnotationAttribute.java:144)
at org.openrewrite.java.AddOrUpdateAnnotationAttribute$1.visitAnnotation(AddOrUpdateAnnotationAttribute.java:78)
at org.openrewrite.java.tree.J$Annotation.acceptJava(J.java:220)
at org.openrewrite.java.tree.J.accept(J.java:60)
at org.openrewrite.TreeVisitor.visit(TreeVisitor.java:206)
at org.openrewrite.TreeVisitor.visitAndCast(TreeVisitor.java:285)
at org.openrewrite.java.JavaVisitor.lambda$visitVariableDeclarations$23(JavaVisitor.java:873)
at org.openrewrite.internal.ListUtils.lambda$map$0(ListUtils.java:141)
at org.openrewrite.internal.ListUtils.map(ListUtils.java:123)
at org.openrewrite.internal.ListUtils.map(ListUtils.java:141)
at org.openrewrite.java.JavaVisitor.visitVariableDeclarations(JavaVisitor.java:873)
at org.openrewrite.java.JavaIsoVisitor.visitVariableDeclarations(JavaIsoVisitor.java:240)
at org.openrewrite.java.JavaIsoVisitor.visitVariableDeclarations(JavaIsoVisitor.java:31)
at org.openrewrite.java.tree.J$VariableDeclarations.acceptJava(J.java:5149)
at org.springframework.sbm.jee.jaxrs.recipes.MandatoryRequestParameter$MandatoryRequestParameterVisitor.makeRequestParamMandatory(MandatoryRequestParameter.java:45)
at org.springframework.sbm.jee.jaxrs.recipes.MandatoryRequestParameter$MandatoryRequestParameterVisitor.lambda$visitMethodDeclaration$0(MandatoryRequestParameter.java:33)
You can get the results you are looking for by using a declarative recipe. You can create a rewrite.yml file in the root of a project and use the rewrite's Maven or Gradle build plugin to apply that recipe.
type: specs.openrewrite.org/v1beta/recipe
name: org.example.MandatoryRequestParameter
displayName: Make Spring `RequestParam` mandatory
description: Add `required` attribute to `RequestParam` and set the value to `true`.
recipeList:
- org.openrewrite.java.AddOrUpdateAnnotationAttribute:
annotationType: org.springframework.web.bind.annotation.RequestParam
attributeName: required
attributeValue: "true"
If using Maven, you can activate that recipe by adding the plugin to your pom.xml:
<plugin>
<groupId>org.openrewrite.maven</groupId>
<artifactId>rewrite-maven-plugin</artifactId>
<version>4.38.0</version>
<configuration>
<activeRecipes>
<recipe>org.example.MandatoryRequestParameter</recipe>
</activeRecipes>
</configuration>
</plugin>
See https://docs.openrewrite.org/getting-started/getting-started for more details on how to use the build plugins.
However, if you want to restrict the change to only specific parameters, while still using the above recipe, you can write an imperative recipe.
public class MandatoryRequestParameter extends Recipe {
private static final String REQUEST_PARAM_FQ_NAME = "org.springframework.web.bind.annotation.RequestParam";
#Override
public #NotNull String getDisplayName() {
return "Make Spring `RequestParam` mandatory";
}
#Override
public String getDescription() {
return "Add `required` attribute to `RequestParam` and set the value to `true`.";
}
#Override
protected TreeVisitor<?, ExecutionContext> getSingleSourceApplicableTest() {
// This optimization means that your visitor will only run if the source file
// has a reference to the annotation.
return new UsesType<>(REQUEST_PARAM_FQ_NAME);
}
#Override
protected #NotNull JavaVisitor<ExecutionContext> getVisitor() {
JavaIsoVisitor addAttributeVisitor = new AddOrUpdateAnnotationAttribute(
REQUEST_PARAM_FQ_NAME, "required", "true", false
).getVisitor();
return new JavaIsoVisitor<ExecutionContext>() {
#Override
public J.Annotation visitAnnotation(J.Annotation annotation, ExecutionContext ctx) {
J.Annotation a = super.visitAnnotation(annotation, ctx);
if (!TypeUtils.isOfClassType(a.getType(), REQUEST_PARAM_FQ_NAME)) {
return a;
}
// The visitor provides a cursor via the `getCusor()` method, and we can use that to navigate
// up to the parent. So, in this case, when we visit the annotation, we can navigate to the
// variable declaration upon which it is defined
J.VariableDeclarations variableDeclaration = getCursor().getParent().getValue();
// This is demonstrating two different ways we might restrict the change:
// - If the parameter's type is a java.lang.Number. Note, this will change all parameters that are
// subtypes of java.lang.Number
// - If the parameter name is equal to "fred"
JavaType paramType = variableDeclaration.getType();
if (TypeUtils.isAssignableTo("java.lang.Number", paramType) ||
variableDeclaration.getVariables().get(0).getSimpleName().equals("fred")) {
// If there is a match, we simple delegate to nested visitor.
return (J.Annotation) addAttributeVisitor.visit(a, ctx, getCursor());
}
return a;
}
};
}
}
}
Here is an example using OpenRewrite's test harness:
#Test
void requiredRequestParam() {
rewriteRun(
spec -> spec
.recipe(new MandatoryRequestParameter())
.parser(JavaParser.fromJavaVersion().classpath("spring-web")),
java(
"""
import org.springframework.web.bind.annotation.RequestParam;
class ControllerClass {
public String sayHello (
#RequestParam(value = "fred") String fred,
#RequestParam(value = "lang") String lang,
#RequestParam(value = "aNumber") Long aNumber
) {
return "Hello";
}
}
""",
"""
import org.springframework.web.bind.annotation.RequestParam;
class ControllerClass {
public String sayHello (
#RequestParam(required = true, value = "fred") String fred,
#RequestParam(value = "lang") String lang,
#RequestParam(required = true, value = "aNumber") Long aNumber
) {
return "Hello";
}
}
"""
)
);
}
Hopefully, this helps!

Convert List of Enums to List of String for Spring #RequestParam using feign client

I have an enum class as such:
ONE("1", "Description1"),
TWO("2", "Description2");
String value;
String description;
MyEnum(String value, String description) {
this.value = value;
this.description = description;
}
#Override
public String toString() {
return this.value;
}
#JsonValue
public String value() {
return this.value;
}
The API I am interacting with is expecting a param with type String and the values can be comma separated.
For example: api.com/test?param1=1,2
I configured a feign client with the url api.com/test
And then created a POJO like so
public class POJO {
private List<MyEnum> param1;
}
And in my feign client I have:
#RequestMapping(method = RequestMethod.GET)
MyResponse getResponse(#SpringQueryMap POJO request);
Is it possible to somehow turn the List of Enums to a List of String before the API call is made via some Spring approach?
As of right now, when I pass a List of Enums, it is only taking into account the last Enum within this list.
UPDATE: I annotated the property I want to convert to a list using #JsonSerialize(converter=abc.class). However #SpringQueryMap doesn't seem to honor that serialization..
Yes is possible, you need to create an interceptor and in that method do the mapping.
This topic may be for you.
Spring - Execute code before controller's method is invoked
So turns out #JsonSerialize was not working with #SpringQueryMap
So I did have to add an interceptor.
Like so:
public class MyInterceptor implements RequestInterceptor {
#Override
public void apply(RequestTemplate requestTemplate) {
if(requestTemplate.queries().containsKey("param1")) {
requestTemplate.query("param1", convert(requestTemplate.queries().get("param1")));
}
}
//convert list to a string
public String convert(Collection<String> values) {
final String s = String.join(",", values.stream().map(Object::toString).collect(Collectors.toList()));
return s;
}
}
And then in my Feign config class added this:
#Bean
public MyInterceptor myInterceptor() {
return new MyInterceptor();
}

How to write a query using only certain parts of an object with Spring JPA

I feel like this should be pretty straightforward, but I'm not sure about the actual code for it. Basically, I have my rest controller taking in 6 arguments, passing that through the Service and then using those arguments to build the object inside of the ServiceImplementation. From there I return a call to my repo using the object I just made. This call should attempt to query the database specific parameters of the object.
This query is the part where I'm not sure how to write using Spring JPA standards. I'd like to just use the variables I set my object with, but I'm not sure if I'll have to write out a query or if spring JPA can make it a bit more simple?
Code:
Controller:
#RestController
public class exampleController {
#Autowired
private ExampleService exampleService;
#GetMapping("/rest/example/search")
public exampleObj searchExample (#RequestParam(value = "exLetter") String exLetter,
#RequestParam(value = "exLang") String exLang, #RequestParam(value = "exType")int exType,
#RequestParam(value = "exMethod") String exMethod, #RequestParam(value = "exCd") String exCd,
#RequestParam(value = "exOrg") String exOrg) {
return exampleService.getExampleLetter(exLetter, exLang, exType, exMethod, exCd, exOrg);
}
}
ExampleSerivce:
public interface ExampleService {
public ExampleLetter getExampleLetter(String exLetter, String exLang, int exType, String exMethod, String exCd, String exOrg);
}
ExampleServiceImplementation:
#Service
public class ExampleServiceImpl implements ExampleService {
#Autowired
private ExampleRepository exampleRepo;
#Override
public ExampleLetter getExampleLetter(String exLetter, String exLang, int exType, String exMethod, String exCd, String exOrg) {
ExampleLetter examp = new ExampleLetter();
examp.setExCd(exCd);
examp.getKey().setExampleNumber(exLetter);
examp.getKey().setLanguageType(exLang);
examp.getKey().setMethod(exMethod);
examp.getKey().setMarketOrg(exOrg);
examp.getKey().setType(exType);
return exampleRepo.findExampleLetter(examp);
}
}
Repo:
#Repository
public interface ExampleRepository extends CrudRepository<ExampleLetter, ExampleLetterKey> {
}
If I understand it correctly, you are trying to make a dinamic query, based on filtering values that may or may not be there. If that's the case, you can use the Specification class to create the query dinamically:
First, in your Repository class, extend JpaSpecificationExecutor<ExampleLetter>:
#Repository
public interface ExampleRepository extends CrudRepository<ExampleLetter, ExampleLetterKey>, JpaSpecificationExecutor<ExampleLetter> {
}
Now, you will need a method (I'd sugest you put it in an specific class, for organization sake) to generate the query itself:
public class GenerateQueryForExampleLetter {
ExampleLetter exampleLetter;
public Specification<ExampleLetter> generateQuery() {
return new Specification<ExampleLetter>() {
private static final long serialVersionUID = 1L;
#Override
public Predicate toPredicate(Root<ExampleLetter> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
Predicate pred = null;
List<Predicate> predicates = new ArrayList<Predicate>();
if (this.exampleLetter.getExCd()!= null && !this.exampleLetter.getExCd().isEmpty()) {
predicates.add(builder.equal(root.<String>get("exCd"), this.exampleLetter.getExCd()));
}
...................
if (this.exampleLetter.getTheFieldYouNeed()!= null && !getTheFieldYouNeed.isEmpty()) {
predicates.add(builder.equal(root.<TheTypeOfTheField>get("theFieldYouNeed"), this.exampleLetter.getTheFieldYouNeed()));
}
if (!predicates.isEmpty()) {
pred = builder.and(predicates.toArray(new Predicate[] {}));
}
return pred;
}
};
}
public void setExampleLetter (ExampleLetter el) {
this.exampleLetter = el;
}
}
Finally, in your service class:
#Override
public ExampleLetter getExampleLetter(String exLetter, String exLang, int exType, String exMethod, String exCd, String exOrg) {
ExampleLetter examp = new ExampleLetter();
examp.setExCd(exCd);
examp.getKey().setExampleNumber(exLetter);
examp.getKey().setLanguageType(exLang);
examp.getKey().setMethod(exMethod);
examp.getKey().setMarketOrg(exOrg);
examp.getKey().setType(exType);
GenerateQueryForExampleLetter queryGenerator = new GenerateQueryForExampleLetter ();
queryGenerator.setExampleLetter(examp);
return exampleRepo.findAll(queryGenerator.generateQuery());
}
Note that the JpaSpecificationExecutor interface adds a few utility methods for you to use which, besides filtering, supports sorting and pagination.
For more details, check here, here, or this answer.

How to programmatically replace Spring's NumberFormatException with a user-friendly text?

I am working on a Spring web app and i have an entity that has an Integer property which the user can fill in when creating a new entity using a JSP form. The controller method called by this form is below :
#RequestMapping(value = {"/newNursingUnit"}, method = RequestMethod.POST)
public String saveNursingUnit(#Valid NursingUnit nursingUnit, BindingResult result, ModelMap model)
{
boolean hasCustomErrors = validate(result, nursingUnit);
if ((hasCustomErrors) || (result.hasErrors()))
{
List<Facility> facilities = facilityService.findAll();
model.addAttribute("facilities", facilities);
setPermissions(model);
return "nursingUnitDataAccess";
}
nursingUnitService.save(nursingUnit);
session.setAttribute("successMessage", "Successfully added nursing unit \"" + nursingUnit.getName() + "\"!");
return "redirect:/nursingUnits/list";
}
The validate method simply checks if the name already exists in the DB so I did not include it. My issue is that, when I purposely enter text in the field, I would like to have a nice message such as "The auto-discharge time must be a number!". Instead, Spring returns this absolutely horrible error :
Failed to convert property value of type [java.lang.String] to required type [java.lang.Integer] for property autoDCTime; nested exception is java.lang.NumberFormatException: For input string: "sdf"
I fully understand why this is happening but i cannot for the life of me figure out how to, programmatically, replace Spring's default number format exception error message with my own. I am aware of message sources which can be used for this type of thing but I really want to achieve this directly in the code.
EDIT
As suggested, i built this method in my controller but i'm still getting Spring's "failed to convert property value..." message :
#ExceptionHandler({NumberFormatException.class})
private String numberError()
{
return "The auto-discharge time must be a number!";
}
OTHER EDIT
Here is the code for my entity class :
#Entity
#Table(name="tblNursingUnit")
public class NursingUnit implements Serializable
{
private Integer id;
private String name;
private Integer autoDCTime;
private Facility facility;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
public Integer getId()
{
return id;
}
public void setId(Integer id)
{
this.id = id;
}
#Size(min = 1, max = 15, message = "Name must be between 1 and 15 characters long")
#Column(nullable = false, unique = true, length = 15)
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
#NotNull(message = "The auto-discharge time is required!")
#Column(nullable = false)
public Integer getAutoDCTime()
{
return autoDCTime;
}
public void setAutoDCTime(Integer autoDCTime)
{
this.autoDCTime = autoDCTime;
}
#ManyToOne (fetch=FetchType.EAGER)
#NotNull(message = "The facility is required")
#JoinColumn(name = "id_facility", nullable = false)
public Facility getFacility()
{
return facility;
}
public void setFacility(Facility facility)
{
this.facility = facility;
}
#Override
public boolean equals(Object obj)
{
if (obj instanceof NursingUnit)
{
NursingUnit nursingUnit = (NursingUnit)obj;
if (Objects.equals(id, nursingUnit.getId()))
{
return true;
}
}
return false;
}
#Override
public int hashCode()
{
int hash = 3;
hash = 29 * hash + Objects.hashCode(this.id);
hash = 29 * hash + Objects.hashCode(this.name);
hash = 29 * hash + Objects.hashCode(this.autoDCTime);
hash = 29 * hash + Objects.hashCode(this.facility);
return hash;
}
#Override
public String toString()
{
return name + " (" + facility.getCode() + ")";
}
}
YET ANOTHER EDIT
I am able to make this work using a message.properties file on the classpath containing this :
typeMismatch.java.lang.Integer={0} must be a number!
And the following bean declaration in a config file :
#Bean
public ResourceBundleMessageSource messageSource()
{
ResourceBundleMessageSource resource = new ResourceBundleMessageSource();
resource.setBasename("message");
return resource;
}
This gives me the correct error message instead of the Spring generic TypeMismatchException / NumberFormatException which i can live with but still, I want to do everything programmatically wherever possible and I'm looking for an alternative.
Thank you for your help!
You may be able to override that messaging by providing an implementation of the Spring DefaultBindingErrorProcessor similar to what is done here:
Custom Binding Error Message with Collections of Beans in Spring MVC
You can annotate a method with:
#ExceptionHandler({NumberFormatException.class})
public String handleError(){
//example
return "Uncorrectly formatted number!";
}
and implement whatever you want to do in case the exception of that type is thrown. The given code will handle exceptions happened in the current controller.
For further reference consult this link.
To make global error handling you can use #ControllerAdvice in the following way:
#ControllerAdvice
public class ServiceExceptionHandler extends ResponseEntityExceptionHandler {
#ExceptionHandler({NumberFormatException.class})
public String handleError(){
//example
return "Uncorrectly formatted number!";
}
}
#Martin, I asked you about the version because #ControllerAdvice is available starting with version 3.2.
I would recommend you to use #ControllerAdvice, which is an annotation that allows you to write code that is sharable between controllers(annotated with #Controller and #RestController), but it can also be applied only to controllers in specific packages or concrete classes.
ControllerAdvice is intended to be used with #ExceptionHandler, #InitBinder, or #ModelAttribute.
You set the target classes like this #ControllerAdvice(assignableTypes = {YourController.class, ...}).
#ControllerAdvice(assignableTypes = {YourController.class, YourOtherController.class})
public class YourExceptionHandler{
//Example with default message
#ExceptionHandler({NumberFormatException.class})
private String numberError(){
return "The auto-discharge time must be a number!";
}
//Example with exception handling
#ExceptionHandler({WhateverException.class})
private String whateverError(WhateverException exception){
//do stuff with the exception
return "Whatever exception message!";
}
#ExceptionHandler({ OtherException.class })
protected String otherException(RuntimeException e, WebRequest request) {
//do stuff with the exception and the webRequest
return "Other exception message!";
}
}
What you need to keep in mind is that if you do not set the target and you define multiple exception handlers for the same exceptions in different #ControllerAdvice classes, Spring will apply the first handler that it finds. If multiple exception handlers are present in the same #ControllerAdvice class, an error will be thrown.
Solution 1: StaticMessageSource as Spring bean
This gives me the correct error message instead of the Spring generic TypeMismatchException / NumberFormatException which i can live with but still, I want to do everything programmatically wherever possible and I'm looking for an alternative.
Your example uses ResourceBundleMessageSource which uses resource bundles (such as property files). If you want to use everything programmatically, then you could use a StaticMessageSource instead. Which you can then set as a Spring bean named messageSource. For example:
#Configuration
public class TestConfig {
#Bean
public MessageSource messageSource() {
StaticMessageSource messageSource = new StaticMessageSource();
messageSource.addMessage("typeMismatch.java.lang.Integer", Locale.getDefault(), "{0} must be a number!");
return messageSource;
}
}
This is the simplest solution to get a user friendly message.
(Make sure the name is messageSource.)
Solution 2: custom BindingErrorProcessor for initBinder
This solution is lower level and less easy than solution 1, but may give you more control:
public class CustomBindingErrorProcessor extends DefaultBindingErrorProcessor {
public void processPropertyAccessException(PropertyAccessException ex, BindingResult bindingResult) {
Throwable cause = ex.getCause();
if (cause instanceof NumberFormatException) {
String field = ex.getPropertyName();
Object rejectedValue = ex.getValue();
String[] codes = bindingResult.resolveMessageCodes(ex.getErrorCode(), field);
Object[] arguments = getArgumentsForBindError(bindingResult.getObjectName(), field);
boolean useMyOwnErrorMessage = true; // just so that you can easily see to default behavior one line below
String message = useMyOwnErrorMessage ? field + " must be a number!" : ex.getLocalizedMessage();
FieldError error = new FieldError(bindingResult.getObjectName(), field, rejectedValue, true, codes, arguments, message);
error.wrap(ex);
bindingResult.addError(error);
} else {
super.processPropertyAccessException(ex, bindingResult);
}
}
}
#ControllerAdvice
public class MyControllerAdvice {
#InitBinder
public void initBinder(WebDataBinder binder) {
BindingErrorProcessor customBindingErrorProcessor = new CustomBindingErrorProcessor();
binder.setBindingErrorProcessor(customBindingErrorProcessor);
}
}
It basically intercepts the call to DefaultBindingErrorProcessor.processPropertyAccessException and adds a custom FieldError message when binding failed with a NumberFormatException.
Example code without Spring Web/MVC
In case you want to try it without Spring Web/MVC, but just plain Spring, then you could use this example code.
public class MyApplication {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(MyConfig.class);
Validator validator = context.getBean(LocalValidatorFactoryBean.class);
// Empty person bean to be populated
Person2 person = new Person2(null, null);
// Data to be populated
MutablePropertyValues propertyValues = new MutablePropertyValues(List.of(
new PropertyValue("name", "John"),
// Bad value
new PropertyValue("age", "anInvalidInteger")
));
DataBinder dataBinder = new DataBinder(person);
dataBinder.setValidator(validator);
dataBinder.setBindingErrorProcessor(new CustomBindingErrorProcessor());
// Bind and validate
dataBinder.bind(propertyValues);
dataBinder.validate();
// Get and print results
BindingResult bindingResult = dataBinder.getBindingResult();
bindingResult.getAllErrors().forEach(error ->
System.out.println(error.getDefaultMessage())
);
// Output:
// "age must be a number!"
}
}
#Configuration
class MyConfig {
#Bean
public LocalValidatorFactoryBean validator() {
return new LocalValidatorFactoryBean();
}
}
class Person2 {
#NotEmpty
private String name;
#NotNull #Range(min = 20, max = 50)
private Integer age;
public String getName() { return name; }
public void setName(String name) { this.name = name; }
public Integer getAge() { return age; }
public void setAge(Integer age) { this.age = age; }
public Person2(String name, Integer age) {
this.name = name;
this.age = age;
}
}
Handle NumberFormatException.
try {
boolean hasCustomErrors = validate(result, nursingUnit);
}catch (NumberFormatException nEx){
// do whatever you want
// for example : throw custom Exception with the custom message.
}

MapStruct: mapping from java.util.Map to Bean?

I currently have a Map<String, String> that contains values in the form key = value and I would like to "expand" those into a real object.
Is it possible to automate that with MapStruct and how would I do that?
To clarify: The code I would write by hand would look something like this:
public MyEntity mapToEntity(final Map<String, String> parameters) {
final MyEntity result = new MyEntity();
result.setNote(parameters.get("note"));
result.setDate(convertStringToDate(parameters.get("date")));
result.setCustomer(mapIdToCustomer(parameters.get("customerId")));
// ...
return result;
}
Method 1
The MapStruct repo gives us useful examples such as Mapping from map.
Mapping a bean from a java.util.Map would look something like :
#Mapper(uses = MappingUtil.class )
public interface SourceTargetMapper {
SourceTargetMapper MAPPER = Mappers.getMapper( SourceTargetMapper.class );
#Mappings({
#Mapping(source = "map", target = "ip", qualifiedBy = Ip.class),
#Mapping(source = "map", target = "server", qualifiedBy = Server.class),
})
Target toTarget(Source s);
}
Notice the use of the MappingUtil class to help MapStruct figuring out how to correctly extract values from the Map :
public class MappingUtil {
#Qualifier
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.SOURCE)
public #interface Ip {
}
#Qualifier
#Target(ElementType.METHOD)
#Retention(RetentionPolicy.SOURCE)
public static #interface Server {
}
#Ip
public String ip(Map<String, Object> in) {
return (String) in.get("ip");
}
#Server
public String server(Map<String, Object> in) {
return (String) in.get("server");
}
}
Method 2
As per Raild comment on the issue related to this post, it is possible to use MapStruct expressions to achieve similar results in a shorter way :
#Mapping(expression = "java(parameters.get(\"name\"))", target = "name")
public MyEntity mapToEntity(final Map<String, String> parameters);
No note on performance though and type conversion may be trickier this way but for a simple string to string mapping, it does look cleaner.
Since version 1.5.0.Beta1 (Jul 2021) MapStruct supports mapping from Map to POJO.
Example:
#Mapper
public interface CustomerMapper {
#Mapping(target = "name", source = "customerName")
Customer toCustomer(Map<String, String> map);
}

Categories

Resources