How to access field value in a JSR-303 message? - spring

I would like to customize my error message in the following way:
Assume following declaration of a class Person:
#Size(min=10, max=200, message="{name.size}")
private String name;
Within the declared error message in ValidationMessages.properties I would like to output the field value as well, i.e. I would like to do something like this:
name.size=The name '{name}' is invalid, its size must be between {min} and {max}
Assume the content of the field 'name' is “abc”. Then the error message should look like this:
The name 'abc' is invalid, its size must be between 10 and 200
The substitution for min and max works, but how can I do this for the field value?

With BeanValidation 1.0 I think there is a way to get the value using a message interpolater. I believe with the hibernate implementation of bean validation 1.0 this was available as part of their bundle.
With BeanValidation 1.1 this became available via EL expressions. The field value is now accessible via the name validatedValue. If you could try to use the latest version. Your message would look like this:
name.size=The name '${validatedValue}' is invalid, its size must be between {min} and {max}

Related

Not able to read int values from Kubernetese config maps

I am trying to deploy a springboot application on kubernetese. I have stored all environment variable in config map and trying to read value from there. There are certain properties where we need to read int values.
In our code, it looks something like this :
application.properties :
TOKEN_RETRY_COUNT=3
As we have to read it from ConfigMap, we have updated our application.properties as mentioned below:
Update application.properties :
TOKEN_RETRY_COUNT=${STARGATE_TOKEN_RETRY_LIMIT}
Config Maps
The values are configured are like this in the Config Maps. I had to put double quotes as it wasn't allowed without any quote.
"STARGATE_TOKEN_RETRY_LIMIT": "3",
Now, when I am trying to read these values after deploying it on kubernetese, I am getting below error :
For STARGATE_TOKEN_RETRY_LIMIT :
Failed to convert value of type 'java.lang.String' to required type 'int'; nested exception is java.lang.NumberFormatException: For input string: "STARGATE_TOKEN_RETRY_LIMIT"
For now, I had updated code to take this value as String and then parse it as int but this is not ideal way. There should be some standard way to take different types.
If we can't handle different type in Config Maps, then what what would be ideal way to pass different application properties for Springboot application on kubernetese ?
I don't think the issue is related to the property value (3) being specified as a string ("3"). If you read the error message carefully you will see that the NumberFormatException is caused by an attempt to parse STARGATE_TOKEN_RETRY_LIMIT (literally) to a an int. Probably there is something wrong with the way the config map is passed to the application/container.

Hyperledger Fabic 2.2.0 Error handling success response. Value did not match schema

I am using Hyperledger Fabric 2.2.0 and fabric-network 2.1 (not that important).
My chaincode is written in Go. So I have some structs which have ,omitempty in JSON tag. Here is my struct:
type LeaseDetails struct {
EndOfTerm string `json:"endOfTerm"`
Info string `json:"info,omitempty"`
Option string `json:"option,omitempty"`
}
But I am getting the following error as a return value from my chaincode:
peer=peer0.org1.example.com:7051, status=500, message=Error handling success response. Value did not match schema:
1. return.0.leaseDetails: info,omitempty is required
2. return.0.leaseDetails: option,omitempty is required
If I remove ,omitempty from my struct, and provide default value everything works fine.
In the docs for fabric-contract-api-go it is mentioned that there is some kind of serializer built upon json marshal/unmarshal, but to me it doesn't seem to detect the ,omitempty keyword.
Was this intentional? Or am I missing something here?
Thanks in advance
I got the answer on Hyperledger Chat from user #awjh.
This is as intended, the json is compared against the metadata schema.
By default all fields are required, using omitempty will mean that the
JSON process will remove that field when it has no value. This means a
required field will be missing. To fix this add a metadata tag to mark
the field as optional metadata:",optional"
So in my case, the solution is:
type LeaseDetails struct {
EndOfTerm string `json:"endOfTerm"`
Info string `json:"info,omitempty" metadata:",optional"`
Option string `json:"option,omitempty" metadata:",optional"`
}

ConstraintViolationException - extract field name which caused exception

I'm using hibernate-validator with a JAX-RS service to validate query parameters using #NotNull:
#GET
public Response doSomething(#NotNull #QueryParam("myParam") String myParam) {...}
This works as expected and throws a ConstraintViolationException if myParam is null. I'd like to extract the param name which is associated to the violation (e.g. myParam), and return that in the response message to the client but there does not appear to be an obvious way of extracting this from the exception. Can someone provide some insight?
As of BeanValidation 1.1 there is a ParameterNameProvider contract which makes parameter name extraction configurable. As mentioned in the other answer, with Java 8 you can get the parameter names in the byte code provided you compile with the -parameters flag. Use the ReflectionParameterNameProvider in this case. However, even with Java 7 you can get parameter names, for example by using the ParanamerParameterNameProvider. This parameter name provider is based on Paranamer and there are several ways to set it up.
This only works if you're using Java 8, as prior to Java 8 the actual parameter name was lost at compile time. Its now retained, assuming you compile and run at Java 8. See also http://docs.jboss.org/hibernate/validator/5.2/reference/en-US/html_single/#_java_8_support

Stripes Framework expression validation on property

I am trying to add expression validation on my property on actionbean but I am unable to make it work. I have even tried with integers like this >0 but still the same exception is thrown. Below is the code
#Validate(required=true, minvalue=1, expression="${this > maxBudget}")
int minBudget;
int maxBudget;
I am getting the below exception:
net.sourceforge.stripes.exception.StripesRuntimeException: Could not parse the EL expression being used to validate
field minBudget. This is not a transient error. Please double check the following expression for errors: ${this > maxBudget}
caused by
javax.el.ELException: The identifier [this] is not a valid Java identifier as required by section 1.19 of the EL specification (Identifier ::= Java language identifier).
This check can be disabled by setting the system property org.apache.el.parser.SKIP_IDENTIFIER_CHECK to true.
I have tried few variation, but every time it throws this exception.
Can some one please point out the mistake I am doing here
thanks
If you want to make sure minBudget is larger than maxBudget (isn't that the other way around?) you could just do:
#Validate(required=true, minvalue=1, expression="${minBudget > maxBudget}")
For greater flexibility you could consider implementing a custom validation method:
#ValidationMethod(on={"show"})
public void checkBudgetRange(ValidationErrors errors) {
if (minBudget < maxBudget)
errors.addGlobalError( new SimpleError("This is not good..."));
// all sorts of other checks to your liking
}
The on array argument holds the name(s) of the event handler(s) for which you want to perform this validation method. So in the example here that would be public Resolution show().
There's an excellent explanation at the Stripes Framework site at https://stripesframework.atlassian.net/wiki/display/STRIPES/Validation+Reference
UPDATE:
If you want to make use of the this keyword in validation expressions you may need to add a VM argument to your server (tested this on Tomcat 8):
-Dorg.apache.el.parser.SKIP_IDENTIFIER_CHECK=true
Otherwise the abovementioned error may be thrown.
The default value of org.apache.el.parser.SKIP_IDENTIFIER_CHECK was changed from true to false as of version 7 in Tomcat.
https://tomcat.apache.org/tomcat-6.0-doc/config/systemprops.html
https://tomcat.apache.org/tomcat-7.0-doc/config/systemprops.html

Grails define custom error message for command object

I am writing a Grails (2.3.3 currently) application and have created a validateable command object similar to the following:
#Validateable
class MyCustomCommand {
String name
static constraints = {
name blank: false
}
}
In my i18n/messages.properties file I defined the following properties to override the default error messages.
MyCustomCommand.name.blank=Name must be provided.
MyCustomCommand.name.null=Name must be provided.
Which per the Grails documentation should be of the format [Class Name].[Property Name].[Constraint Code] as I have done. When I run my application if I leave the value blank I still get the default message for a null property.
I also tried following the example of the default messages and defining them a follows, but still get the default message.
MyCustomCommand.name.blank.message=Name must be provided.
MyCustomCommand.name.null.message=Name must be provided.
I am assuming that I am missing something simple here, but have yet to stumble upon what. Any suggestions on what I am doing incorrectly?
It is simple indeed. Message should look like:
myCustomCommand.name.blank=Name must be provided.
myCustomCommand.name.nullable=Name must be provided.
//className.propertyName.blank (camelCase with first letter of class name lower)
So, as I anticipated it was something simple. I was using the defaults as an example which used null where as what I really needed was nullable. Which does make sense as that matches the constraint name.
Therefore the correct version is:
myCustomCommand.name.blank=Name must be provided.
myCustomCommand.name.nullable=Name must be provided.

Resources