Should Hibernate-Validator ignore Boolean (object) getters when prefixed with "is" rather than "get"? - hibernate-validator

public class YourAnnotatedBean {
private Boolean activated;
#Valid
#NotNull
public Boolean isActivated() {
return activated;
}
public void setOn(Boolean activated) {
this.activated = activated;
}
}
Hibernate-validator seems to ignore #NotNull when it is on a Boolean getter called isActivated. If I rename it to getActivated, the constraint is enforced. I would just rename the getter, but this is coming from swagger-codegen.
My question is whether this is intentional or a bug? As far as I can tell, the JavaBeans spec doesn't mention Boolean wrapper objects. If this is not a bug, we'll need to update swagger-codegen to not use the "is" prefix for Booleans.

In the Java Bean convention, "is" is a valid prefix only for a primitive boolean.
Here you have a Boolean so it should really be getActivated(). That's why HV ignores it.
Any chance you could add the constraint to the property instead of the getter?
We have this long term project of allowing alternative property selectors but, for now, it's just a project (see https://hibernate.atlassian.net/browse/HV-1363).

Related

Mapping Java Optional with DynamoDBMapper annotations

Is there a clean way to map Optional fields with DynamoDBMapper, for both basic types and arbitrary/custom objects?
I believe one option would be to implement DynamoDBTypeConverter for optionals of basic types (Optional<String>, Optional<Integer>, etc). But, in addition to being a bit dirty, this would not work for custom objects.
I am looking for some sort of "chaining" behaviour of converters, where the default converter is applied first and the result wrapped in case of optional fields.
Is there a way to specify this behaviour?
#DynamoDBTable
public class MyModel {
#DynamoDBAttribute
private Optional<String> someStringField;
#DynamoDBAttribute
private Optional<AnotherModel> someAnotherModelField;
...
}
#DynamoDBDocument
public class AnotherModel {
}
For what you want to do, I believe the custom converters is the proper way.
Create a class for example:
class SomeAnotherModelOptionalConverter implements DynamoDBTypeConverter<String, Optional<AnotherModel>> {
#Override
public String convert(Optional<AnotherModel> optional) {
// your conversion from Optional attribute to String DynamoDB attribute
}
#Override
public Optional<AnotherModel> unconvert(String s) {
// your conversion from String DynamoDB attribute to Optional
}
}
Then on your attribute, you add the following tag:
#DynamoDBAttribute
#DynamoDBTypeConverted(converter = SomeAnotherModelOptionalConverter.class)
private Optional<AnotherModel> someAnotherModelField;
Anyways, I would not use an Optional as a field in a class. Instead I would create a getter that has and Optional as a return.
private AnotherModel someAnotherModelField
...
Optional<AnotherModel> getSomeAnotherModelField(){
return Optional.ofNullable(someAnotherModelField);
}
Let me know if that works for you!

How to create custom nested validator with JSR 303?

I am using Hibernate Validator - 5.2.2 (JSR 303).
I am doing a cross field validation, so I need to create a custom validator.
However I have no idea how to do the custom conditional nested validation.
example:
#ValidChildrenIfEnabled
public class MainDto {
public boolean isEnabled;
public List<Child> children;
}
public class Child {
#NotBlank
public String name;
#Range(min = 1, max = 3)
public int age;
}
If I don't need conditional validation, I would put
#Valid on top of "children".
#Valid
public List<Child> children;
Note: I know how to create a custom validator, I just don't know how to create a custom validator that do nested validation that take advantage of existing built-in validator. Thanks!
EDIT:
My payload actually has one more payload, let's say SuperDto.
public class SuperDto {
#Valid
public List<MainDto> mainDtos;
}
And I do validation like this:
validator.validate(superDto);
Interesting use case. Unfortunately, I don't think you can do what you want to do as you can't trigger a validation from isValid().
Supposing that you have other constraints you want to validate in every cases, I think the best workaround is probably to use groups. And to use different groups depending of if isEnabled is true or not.
Anyway, you would have to special case how this bean is validated.

Does Freemarker have any integration for JodaTime?

Are there any ways to easy format Joda DateTime objects in Freemarker? For example with Java dates, we could use the ?string and other directives.
I know I could call toDate and get a Java Date, but I was hoping there was a better way.
You should be able to call the toString(String pattern) method directly from Freemarker:
${dateTime.toString('MM-dd-yy')}
(not tested)
There's even a simpler way of doing this, if you don't want to splatter toString('MM-dd-yy') all over your templates.
Simply extend Freemarker's DefaultObjectWrapper, so that it understands Joda Time out of the box:
public class JodaAwareObjectWrapper extends DefaultObjectWrapper {
#Override
public TemplateModel wrap(final Object obj) throws TemplateModelException {
if (obj == null) { return super.wrap(obj); }
if (obj instanceof LocalDate) { return new SimpleDate(((LocalDate) obj).toDate(), TemplateDateModel.DATE); }
// add support for all desired types here...
return super.wrap(obj);
}
}
and feed this object wrapper to the FreeMarker config when you fire up your FreeMarker engine
Configuration config = // ...
config.setObjectWrapper(new JodaAwareObjectWrapper());
You can then use FreeMarkers standard date built ins, such as ${dateTime?date} in your templates
I do not believe at this time there is any integration in Freemarker for JodaTime. It is pretty easy to put an object in your model for formatting, i.e.
Write a class "MyCustomJodaFormatterBean", with a format(String pattern, DateTime dateTime) method. Put an instance of this in the root.
root.put("joda", new
MyCustomJodaFormatterBean());
Then in freemarker,
${joda.format("MM-dd-yyy", dateTime)}
During parsing of FTL files freemarker builds its internal model of objects. For example java.util.Date expressions are wrapped into freemarker.template.SimpleDate. If expression value of your model is of type org.joda.time.DateTime - which is unknown for freemarker, it will be wrapped by default into freemarker.ext.beans.StringModel, converting your DateTime to string using toString() method.
For example, assume we have in FTL expression like:
med.expiryDate?date <= today?date
Where "med.expiryDate" is of type DateTime.
"med.expiryDate" will be wrapped into freemarker.ext.beans.StringModel and after this "med.expiryDate?date" will be parsed used freemarker.template.Configuration dateFormat. Which can leed to exception if this dateFormat is different then default format of DateTime.toString().
To fix this you need to make Freemarker understand that DateTime is also a date, not a string. Write your custom object wraper:
/**
* Wrapper to make freemarker identify org.joda.time.DateTime objects as date.
* User: evvo
* Date: 5/26/2016
* Time: 18:21
*/
public class DateTimeAwareObjectWrapper extends DefaultObjectWrapper {
#Override
public TemplateModel wrap(Object obj) throws TemplateModelException {
if (obj instanceof DateTime) {
return new SimpleDate(((DateTime) obj).toDate(), getDefaultDateType());
}
return super.wrap(obj);
}
}
And set it into freemarker configuration
configuration.setObjectWrapper(new DateTimeAwareObjectWrapper());
After such change I belive ?string suffix will also work on DateTime expression.

To mock an object, does it have to be either implementing an interface or marked virtual?

or can the class be implementing an abstract class also?
To mock a type, it must either be an interface (this is also called being pure virtual) or have virtual members (abstract members are also virtual).
By this definition, you can mock everything which is virtual.
Essentially, dynamic mocks don't do anything you couldn't do by hand.
Let's say you are programming against an interface such as this one:
public interface IMyInterface
{
string Foo(string s);
}
You could manually create a test-specific implementation of IMyInterface that ignores the input parameter and always returns the same output:
public class MyClass : IMyInterface
{
public string Foo(string s)
{
return "Bar";
}
}
However, that becomes repetitive really fast if you want to test how the consumer responds to different return values, so instead of coding up your Test Doubles by hand, you can have a framework dynamically create them for you.
Imagine that dynamic mocks really write code similar to the MyClass implementation above (they don't actually write the code, they dynamically emit the types, but it's an accurate enough analogy).
Here's how you could define the same behavior as MyClass with Moq:
var mock = new Mock<IMyInterface>();
mock.Setup(x => x.Foo(It.IsAny<string>())).Returns("Bar");
In both cases, the construcor of the created class will be called when the object is created. As an interface has no constructor, this will normally be the default constructor (of MyClass and the dynamically emitted class, respectively).
You can do the same with concrete types such as this one:
public class MyBase
{
public virtual string Ploeh()
{
return "Fnaah";
}
}
By hand, you would be able to derive from MyBase and override the Ploeh method because it's virtual:
public class TestSpecificChild : MyBase
{
public override string Ploeh()
{
return "Ndøh";
}
}
A dynamic mock library can do the same, and the same is true for abstract methods.
However, you can't write code that overrides a non-virtual or internal member, and neither can dynamic mocks. They can only do what you can do by hand.
Caveat: The above description is true for most dynamic mocks with the exception of TypeMock, which is different and... scary.
From Stephen Walther's blog:
You can use Moq to create mocks from both interfaces and existing classes. There are some requirements on the classes. The class can’t be sealed. Furthermore, the method being mocked must be marked as virtual. You cannot mock static methods (use the adaptor pattern to mock a static method).

Can't Deserialize a Nullable KeyValuePair from JSON with ASP.NET AJAX

The following class does not deserialize (but does serialize) using System.Web.Script.Serialization.JavaScriptSerializer.
public class foo {
public KeyValuePair<string, string>? bar {get;set;}
}
The attempt to deserialize results in a System.NullReferenceException when System.Web.Script.Serialization.ObjectConverter.ConvertDictionaryToObject reaches the bar property. (Note, that is a surmise based on the stack trace.)
Changing the property type to KeyValuePair<string,string> fixes the problem, but I'd like to keep the Nullable type if at all possible.
The JSON is exactly what you would expect:
{"foo": {
"bar": {
"Key":"Jean-Luc",
"Value":"Picard"
}
}}
Help?
The reason this happens is that when the JavaScriptSerializer tries to deserialize it will create a new instance of the class (in this the KeyValuePair) and then assign the values to properties.
This causes an issue as the KeyValuePair can only have the key and values assigned as part of the constructor and not via properties so results in an empty key and value.
You will be able to resolve this and the null issue by creating a class that implements JavaScriptConverter and Registering It. I have used the code below to handle a standard KeyValuePair but I am sure you can extend it to handle nulls.
public class DictionaryJavaScriptConverter<k, v> : JavaScriptConverter
{
public override object Deserialize(System.Collections.Generic.IDictionary<string, object> dictionary, System.Type type, System.Web.Script.Serialization.JavaScriptSerializer serializer)
{
return new KeyValuePair<k, v>((k)dictionary["Key"], (v)dictionary["Value"]);
}
public override System.Collections.Generic.IDictionary<string, object> Serialize(object obj, System.Web.Script.Serialization.JavaScriptSerializer serializer)
{
throw new NotImplementedException();
}
public override System.Collections.Generic.IEnumerable<System.Type> SupportedTypes {
get { return new System.Type[] { typeof(KeyValuePair<k, v>) }; }
}
}
Alternately you can create a simple class that has two properties key and value.
You can have a look at this wrapper:
http://www.codeproject.com/KB/aspnet/Univar.aspx
I've successfully Json serialized and deserialized the nullable KeyValue pair using it.

Resources