ConstraintViolationException - extract field name which caused exception - validation

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

Related

Rest camel passing objects between endpoints

Overview.
My camel setup calls two service methods. the response of the first one is passed into the second one and then output the final response as json webpage. Fairly simple nothing too complicated.
Further breakdown to give some more context.
Method_1. Takes in scanId. This works ok. It produces an object called ScheduledScan .class
Method_2. Takes in object previous instance of ScheduledScan .class and returns a list of ConvertedScans scans. Then would like to display said list
Description of the code
#Override
public void configure() throws Exception {
restConfiguration().bindingMode(RestBindingMode.json);
rest("/publish")
.get("/scheduled-scan/{scanId}")
.to("bean:SentinelImportService?method=getScheduledScan").outType(ScheduledScan .class)
.to("bean:SentinelImportService?method=convertScheduledScan");
}
The methods that are called look like the following
ScheduledScan getScheduledScan(#Header("scanId") long scanId);
List<ConvertedScans > convertScheduledScan(#Body ScheduledScan scheduledScans);
It is returning the the following error
No body available of type: path. .ScheduledScan but has value:
of type: java.lang.String on: HttpMessage#0x63c2fd04. Caused by: No type converter available
The following runs without the error, i.e. without method 2. So I think im almost there.
rest("/publish")
.get("/scheduled-scan/{scanId}")
.to("bean:SentinelImportService?method=getScheduledScan");
Now from reading the error it looks like im passing in a HttpMessage not the java object? I'm a bit confused about what to do next? Any advice much appreciated.
I have found some similar questions to this message. However I am looking to pass the java object directly into the service method.
camel-rest-bean-chaining
how-to-share-an-object-between-methods-on-different-camel-routes
You should setup the outType as the last output, eg what the REST response is, that is a List/Array and not a single pojo. So use .outTypeList(ConvertedScans.class) instead.

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

jaxb2-maven-plugin throws Exception when maxOccurs is greater than 5000

When I run the jaxb2-maven-plugin on a legacy xsd it throws this Exception:
Current configuration of the parser doesn't allow a maxOccurs attribute value to be set greater than the value 5,000
Googling this error shows that this is a limit that was put on jaxp for security purposes. It can be disabled in code like this
SAXParserFactory spf = SAXParserFactory.newInstance();
spf.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING,false);
but I need to do this in maven. Also, xjc has a -nv switch to turn off this validation and that looks like the way to go. I can't change the xsd.
What's the syntax for passing the -nv switch in the jaxb2-maven-plugin?
My colleague Vic Ganora found the answer in the source code for the jaxb2-maven-plugin. In the <plugin>...<configuration> element you need to add
<laxSchemaValidation>true</laxSchemaValidation>.

Lpush and Zadd methods of Jedis not found in Jmeter

I have written a beanshell sampler which has the objective of setting the multiple values for a single key. I tried with lpush just for the start. Then I went on using the zadd method which I believe is for adding multiple values for a single key.
But, in both the cases, I am getting an error in the log viewer that the respective method in the jedis class does not exist. How do I go about resolving this error.
I have tried to replace the jedis jar file(current version i am using is: 2.2.1) with the latest version(in the lib folder) in order to ensure the completeness of the methods to be used. But then, while starting the jmeter from command line throws java.lang.VerifyError.
Please let me know the solution for this problem.
Show your code so that we can help more precisely.
Another option is to use this if you only want to read the values:
http://jmeter-plugins.org/wiki/RedisDataSet/

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