spring messages.properties uses variable name - java

Is there a way to use a title instead of a variable name when overriding Spring's default messages using the messages.properties file?
For example, I used this
typeMismatch.java.lang.Integer={0} must be a number.
to create the error message "firstName must be a number.", but I would prefer more readability, like "First Name must be a number.".
Is there any way to do this?

You can customize the property for a specific field of a specific class. Say your model attribute is named foo and it has a property named firstName then you can declare a custom error message for that specific field using:
typeMismatch.foo.firstName=First Name must be a number
You can see this page for more information.

Related

Java validation: Cannot interpolate field name in validation message

I tried the approach mentioned on How get property name in a validation message, but cannot apply it to the following situation.
#Data
public class CompanyRequest {
#PositiveOrZero(message = "validation.amount.positiveOrZero")
int quantity;
// code omitted for brevity
}
Here is my *.properties file having message:
validation.amount.positiveOrZero=The ${fieldName} value must be positive or zero
So, how can I use the property name in the validation message?
${fieldName} could not be retrieved easily inside the annotation without major modifications inside the core mechanism that makes the evaluation.
An easier way to achieve what you want, considering that for each field the name would be different, is the following.
Inside properties file put the property
validation.amount.positiveOrZero= value must be positive or zero
And then define the annotation in the code as
#PositiveOrZero(message = "The quantity {validation.amount.positiveOrZero}")
int quantity;
Edit:
It seems that the property should not be defined in a simple application.properties file but in another file named ValidationMessages.properties in the classpath.
As documented here
setValidationMessageSource(MessageSource messageSource) Specify a
custom Spring MessageSource for resolving validation messages, instead
of relying on JSR-303's default "ValidationMessages.properties" bundle
in the classpath.

Class parameter name for default type in spring-kafka listener

I'm attempting to change the default type value for kafka listener with property "spring.json.value.default.type=" using my own annotation in spring-kafka. Currently, it's possible to overwrite it with following values:
properties="spring.json.value.default.type=com.package.class" which is canonical name of class.
I've made an annotation that sets the following value:
#MyAnnotation(topic = Topics.BUILD_CONFIG_CREATED, defaultType = ConstantsClass.TYPE_HEADER + "prz.student.finger.kafkaBSC.MyObjectDTO")
Is there any way to avoid hard typing the class name?
I would like to implement the option to use the following code(just giving the class that was imported):
#MyAnnotation(topic = Topics.BUILD_CONFIG_CREATED, defaultType = MyObjectDTO.class)
The closest to I've got is adding in my annotation:
#AliasFor(annotation = KafkaListener.class, attribute = "properties")
String defaultType() default headerType()+dtoType().getCanonicalName().toString();
String headerType() default "spring.json.value.default.type=";
Unfortunately, the constraints regarding the compilation time values for class in annotation blocks me from implementing it. Is there any way to inject the cannonical name without hard typing it, or any other way to implement this?
The properties property can contain SpEL (see its Javadocs).
Something like #{#someBean.type.name}; where someBean is a bean with a method public Class<?> getType().

Java Validator custom message still includes the field name

I have the following annotation for a field:
#NotEmpty(message = "unique_name may not be empty")
#JsonProperty("unique_name")
private String uniqueName;
However, when I run a request, the error message I get back is:
uniqueName unique_name may not be empty
Why is the message contains the field name uniqueName? How can I fix this so the message only says unique_name may not be empty?
I believe the plain message string in the annotation is actually using interpolation behind the scenes to prepend the field name. It looks like you probably want to use a custom message.properties file instead. See here: Entity not null validation message
So in src/main/resources/messages you'd have a messages.properties file that contains the message, such as:
error.uniqueName.notEmpty=unique_name may not be empty
Then in your annotation:
#NotEmpty(message = "error.uniqueName.notEmpty")

How to pass a field name to the global message in the properties file

I have the following message in my global-messages.properties file.
errors.integer=${getText(fieldname)} must be an integer.
which works fine with the validation.xml code, but I want to be able use the same message in my java action validation method with the addFieldError() method. My question is how to pass the fieldname to the message. If I use:
addFieldError("seqId", getText("errors.integer"));
I only get the "must be an integer." part of the message. I know I could change the message and use {0} instead of ${getText(fieldname)} but that is not an option because other code uses the message as it is.
First of all: You should really avoid using getText in properties because it is available only in some context.
Second: You should really avoid using fieldname in properties because it is validator specific field.
To achieve what you want, w/o modifying property file, you can create a fieldname property in your action with getter/setter and set its value before using addFieldError.
private String fieldname;
// getter/setter
// ...
fieldname = "seqId";
addFieldError("seqId", getText("errors.integer"));
Someone else showed me another way which worked which I thought I would share.
addFieldError("",getText("seqId")+ getText("errors.integer"));

Struts2 file upload errors

I am a using struts2 file upload and my action class contains 3 private fileds with getter and setters
private File myFile;
private String myFileFileName;
private String myFileContentType;
I have some douts to clarify
We are passing only the file as parameter and bind it to the myFile, So how the application getting the file name and content type?
whenever I use myFileVariableName + "FileName" (if the file variable is myFile then file name variable is myFileFileName, if file is xxx, then file name is xxxFileName), I am getting the output, if i make any change to this format (ie,myFileVariableName + "FileName"), It getting null. Is it mandatory to use this format? Can I change it to any name I desire? If so, then how?
To get the content type, I should use jst "contentType" or myfileVariableName + "contentType". Is it also mandatory?
I assume, if I use a separate bean to store my request variables, all the parameters is bind to that bean variable. But in the case of file upload only the file variable ie, myFile in this example only get and set in the bean. fileFileName and contentType are null. If I declare these variables directly in my action class, then I get the values, but whenever I use a separate bean, only File variable can get and set, and the other two are null. Why?
If I use ModelDriven, the the same case happening, I can only get File variable and the other two variables are null. why?
I am only extending the "struts-default" in my struts.xml and no separate config for file upload, since it dont show any effect in my questions.
Action class for the file upload, declare a File variable to store the user uploaded file, two String variables to store the file name and content type. The fileUpload interceptor will auto inject the uploaded file detail via set 'X' ContentType() and set 'X' FileName(), make sure the method name is spell correctly.
The file upload function is depends on the “fileUpload Interceptor“,
make sure it is included in the Action’s stack. The lucky is, the
default stack is already includes the “fileUpload Interceptor“.
The fields userImageContentType and userImageFileName are optional. If setter method of these fields are provided, struts2 will set the data. This is just to get some extra information of uploaded file. Also follow the naming standard if you providing the content type and file name string. The name should be ContentType and FileName.
For example if the file attribute in action file is private File
uploadedFile, the content type will be uploadedFileContentType and
file name uploadedFileFileName.
Get Set Behaviour in Struts 2 : Assign value to a variable, not property value.
For example,
public class SetTagAction extends ActionSupport{
private String msg;
public String setMsg(String msg) {
this.msg = msg;
}
<s:set var="msg" value="%{'this is a message'}" />
Many Struts 2 developers thought that the set tag var=”msg” will assign the value to the associated action class via setMsg() method.
This is wrong, the set tag will not call the setMsg() method, it will only assign the “value” to a variable named “msg“, not the action’s property value.

Categories