Override error messages in BindingResult - java

I am using Spring MVC 2.5 .
I have fields where numbers should only be the allowed in put. And I get the exact error message on my UI I was looking for . Something like
Failed to convert property value of type [java.lang.String] to required type [java.math.BigDecimal] for property executionThresholdAmount; nested exception is java.lang.NumberFormatException
I don't want to display that kind of message to the user. I do use message.properties file to organize texts to be displayed.
The only thing I need is I wanted to overwrite the error message for specific fields. I couldn't do that but here is the trick I was using for
if(result.hasFieldErrors()){
List<FieldError> bindingErrors=( List<FieldError>)result.getFieldErrors();
BindingResult fieldErrors=new BeanPropertyBindingResult (offerSetting, "offerSetting");
for(FieldError error :bindingErrors ){
String field=error.getField();
fieldErrors.rejectValue(field, "invalid.amount."+field);
}
result=fieldErrors;
#more code
What I am doing is I created BeanPropertyBindingResult which is an implementation of BindingResult and populated the error fields with the message I want and pass the reference to result object so it gets displayed. However, I am now getting both the default messages
like
Failed to convert property value of type [java.lang.String] to required type [java.math.BigDecimal] for property executionThresholdAmount; nested exception is java.lang.NumberFormatException
and also the message I wanted. Something like
"The amount for field price you entered is invalid"
Any better ideas?

Try adding to your messages properties file somethig like this:
typeMismatch.objectClassName.field=Your custom message
In your case:
typeMismatch.offerSetting.amount=The amount for field price you entered is invalid
Works for me :)

Related

Wicket.Ajax.Call.failure: Error while parsing response Value is not a valid ByteString

I'm getting the following error when I try to click on an RadioChoice button.
ERROR: Wicket.Ajax.Call.failure: Error while parsing response: TypeError: Failed to execute 'setRequestHeader' on 'XMLHttpRequest': Value is not a valid ByteString.
I can't provide a code. Any idea about this error.
It must be something in the values of header variable passed to jQuery here.
I guess it is the value of lastFocusId .
I'd recommend you to put a break point and see what values are being set and which one is not valid. Most probably lastFocusId has some Unicode characters which cannot be converted to ByteString.

playframe work can't find the right route

I have a strange problem
this is what I have in routes files
GET /path/list controllers.path.getPaths()
GET /path/:id controllers.path.get(id:Int)
when I try to go <domain>/path/list the following error shows up:
For request 'GET /path/list' [Cannot parse parameter id as Int: For
input string: "list"]
I also tried to change the order in routes file
GET /path/:id controllers.path.get(id:Int)
GET /path/list controllers.path.getPaths()
I still get the same error. so my question is
isn't route supposed to match the first path that matches?
what else could be the problem (e.g. java codes)?
From the code you've provided this should work. The routes are not ambiguous because (from Play documentation):
Many routes can match the same request. If there is a conflict, the first route (in declaration order) is used.
if your routes ordering looks like this:
GET /path/list controllers.path.getPaths()
GET /path/:id controllers.path.get(id:Int)
/path/list will match before attempting to extract/transform the id parameter id:Int from the path and throwing.
If you want Play to transform the incoming parameter into a specific Scala type, you can add an explicit type
The only way this would not work is if you attempted to visit a route that did not match list or was not an Int:
For request 'GET /path/lists' [Cannot parse parameter id as Int: For input string: "lists"]

Get path variable out of HttpMessageNotReadable exception

We have some web services which are being consumed by mobile clients , in which the mobile clients make some request's and we return response to them. Somehow if the client make any invalid request we throw Custom Exceptions .But recently the mobile client has made some request which was out of range for Long variable. The client has different variables for ex ::
{
"accountId":"343"
"Amount":"90909090909090909090"
}
In case of the value for accountId or Amount are made more than 19 digits we get HttpMessageNotReadable exception as the range is out of long value. But from exception i am not able to fetch for which variable the exception has been raised whether for accountId or Amount. From the exception i am getting this information in _path variable but i am not able to fetch it.
And in the path variable i get something like::
[com.Upload["AccountInfo"], com.Info["Account"]]
Does somebody know how to fetch this information.
The following code prints out the field which causes the exception.
InvalidFormatException invalidFormatException = (InvalidFormatException) exception
.getCause();
System.out.println(invalidFormatException.getPath().get(0)
.getFieldName());
#ArunM's answer works as long as the field is in 1st level viz the example given by OP.
But what happens when the field is in nested json? say paymentType has wrong value in the following example?
{
"userType": "CUSTOMER",
"payment": {
"amount": 123456,
"paymentType": "INTERNET_BANKING"
}
}
In the above example, if there's anything wrong with the value of userType, there will be just one element in _path.
But if any value inside the payment is wrong, say for example paymentType, there will be multiple elements in the _path variable. Each element representing the hierarchical attribute.
So for paymentType, _path will have 2 elements as illustrated below:
_path[0].fieldName = "payment"
_path[1].fieldName = "paymentType"
Hence the correct approach is to get the last element in _path as shown below. If needed, we can build the complete path by using all the elements.
InvalidFormatException ifx = (InvalidFormatException) exception.getCause();
System.out.println(ifx.getPath().get(ifx.size() - 1).getFieldName());
This I believe is the right approach to get the invalid attribute name.

Problem in displaying data from database in JSF

i have a problem when i run a page.jsp :
Exception while calling encodeEnd on component : {Component-Path : [Class: javax.faces.component.UIViewRoot,ViewId: /compteListe.jsp][Class: javax.faces.component.html.HtmlDataTable,Id: j_id_jsp_1879226420_1][Class: javax.faces.component.UIColumn,Id: j_id_jsp_1879226420_2][Class: javax.faces.component.html.HtmlOutputText,Id: j_id_jsp_1879226420_4]}
Caused by:
org.apache.jasper.el.JspPropertyNotFoundException - /compteListe.jsp(29,13) '#{l.Identifiant}' Property 'Identifiant' not found on type com.bankonet.bean.Compte
but when i do System.out.println (rs.getString (1));..., it works well and displays data !!
Unless the property name itself actually starts with 2 uppercased characters, the property name in EL needs to start with lowercase, so:
#{l.identifiant}
This requires a public no-arg getter method with name getIdentifiant().
org.apache.jasper.el.JspPropertyNotFoundException - /compteListe.jsp(29,13) '#{l.Identifiant}' Property 'Identifiant' not found on type com.bankonet.bean.Compte
It searches for a Field with name Identifiant in class com.bankonet.bean.Compte with standard setter/getter methods , which it doesn't find and so the error
but when i do System.out.println (rs.getString (1));..., it works well and displays data !!
It doesn't relate to your problem. You need to pass a collection to view to produce view

Bean Validation + Resource Bundle ideas?

Here is what i want to be able to do with bean validation in my JPA entities :
Instead of #NotNull, i would like to do #NotNull(message="keyInMyResourceBundleFile")
I would like also to parameterize the resourceBundle, and i dont know the syntax for it, because it seems to me the message attribute contains only a string.
The parameter itself could be i18n-ed. For example, assuming there's a param attribute for the resourcebundle parameters, in English, #NotNull(message="missing.value", params={"credit card"}) String creditCard; It will be displayed something like this : "Missing required value for field credit card. In Indonesia, it'll be something like "Nilai harus di isi untuk Kartu Kredit. In this example, i cant hardcode the "credit card" because in Indonesia, it's "Kartu Kredit"
Displays the error message defined in the resource bundle on the log file or UI. Im not sure the way on how to do it, should i catch the ConstraintViolationException, get the message, and process the resource bundle by my own code ?
Please share your thoughts on this ?
Thank you !
Regarding 1 + 2
#NotNull(message="{keyInMyResourceBundleFile}")
Curly brackets are the indicator of a parameter substitution
Regarding 3
No idea what you are after. There is no params attribute for #NotNull. I guess you would do
#NotNull(message="{missing.credit.card}")
And of if you place it on another property you would call the key {missing.name}
Regarding 4
The ConstraintViolationException contains the set of *ConstraintViolation*s. Each ConstraintViolation contains the interpolated message as well as the message template. If you want to log it, do it ...

Categories

Resources