Grails define custom error message for command object - validation

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.

Related

Ignore locale on thymeleaf #date.format()

I want to keep date format to fix standard regardless of locale. But however it is by default taking current locale and setting format based on locale.
th:text="${#dates.format(myDate, 'dd-MMM-yyyy')}"
I am always expecting format be like
09-Sep-2015
but with CA locale I am getting 09-de set.-2015
Is there a way to fix this.
UPDATE
This question is not duplicate of This question. My problem is related to locale formatting.
Not sure you are using Maven or Gradle. Add thymeleaf-extras-java8time as your dependency.
and instead of #dates use #temporal and specify locale as parameters as below.
th:text="${#temporals.format(myDate, 'dd-MMM-yyyy','en')}"
But make sure your myDate is in java.time.* format
The #temporals.format function is the correct one to use. However, the third "locale" argument must be a java.util.Locale object, not a string.
The following work:
#temporals.format(myDate, 'dd-MM-yyyy', new java.util.Locale('en'))
#temporals.format(myDate, 'dd-MM-yyyy', #java.util.Locale#ENGLISH)
Note that this is true even if you're working with Kotlin Spring Boot. The syntax in the Thymeleaf template isn't Java, it's an OGNL Expression.
https://commons.apache.org/proper/commons-ognl/language-guide.html
I'll quote the useful syntax used here:
#variable
Context variable reference
#class#method(args)
Static method reference
#class#field
Static field reference
new class(args)
Constructor call
Edit: one other option is to specify the Locale in the Thymeleaf context, if you just want to override the default system Locale. I've included a Kotlin snippet of how that might work:
val context = Context() // org.thymeleaf.Context
context.locale = Locale.ENGLISH
context.setVariable("x", 0)
templateEngine.process("classpath:template.html", context)

SpelParseException: After parsing a valid expression, there is still more data in the expression: 'lcurly({)'

I am trying to condtionally create a component using #ConditionalOnExpression("not ${service.synchronous} && not ${service.disabled}").
I based this on Spring Boot SpEL ConditionalOnExpression check multiple properties, which provides a multi-property conditional as follows: #ConditionalOnExpression("${properties.first.property.enable:true} && ${properties.second.property.startServer:false}")
However, I keep getting:
Caused by: org.springframework.expression.spel.SpelParseException: EL1041E: After parsing a valid expression, there is still more data in the expression: 'lcurly({)'
Those properties are always set in my .properties file so I did not provide a default value with the colon notation. What am I doing wrong?
You will need to provide the default values for your properties like in the example you followed, so update the expression to be:
#ConditionalOnExpression("not ${service.synchronous:false} && not ${service.disabled:true}")
In most such cases the properties your app is reading are not what you expect them to be.
Set a breakpoint on all constructors of SpelParseException. In the debugger you will see the expression that is parsed, that will give show you exactly which properties you are really using.
Maybe you have to go search a little in the stack until you find the right location where you can see the expression.
My mistake was that I had not imported the test properties file in a Spring test.
After I added #TestPropertySource("classpath:/application.properties") to the test class, the properties from the properties file were used.

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

How do I use the appProperties with the ruby api-client

I can't determine how to add custom properties or search for them.
Everything I have tried is giving me a Error - #<Google::Apis::ClientError: invalid: Invalid query> when I attempt to search for them. I can successfully complete other queries but I don't know if the client is setup to work with appProperties (or even properties at all).
Basically I just need the correct syntax for searching and adding since it doesn't appear to be in the documentation.
Assuming you already have a reference to an authorized DriveService, you can search based on appProperties using a q-parameter (documented here), like this:
file_list = drive.list_files(
q: "appProperties has { key='my_app_key' and value='my_val' }",
fields: 'files(id, name, appProperties)',
spaces: 'drive')
If you omit the fields parameter then the search will still work but the properties themselves won't be returned.
Updating appProperties is definitely arcane and the documentation is opaque. What you need is the ID of the file, and a File value object as a container for the attributes to update. Something like this:
new_app_properties = { 'my_app_key' => 'my_val' }
update_f = Google::Apis::DriveV3::File.new(app_properties: new_app_properties)
drive.update_file(file_id, update_f)

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

Resources