Check that each element in collection is not empty - bean-validation

How to simply check that each element in collection of strings is not empty using some annotation?
List<String> strings;

There is no simple way to achieve this with Bean Validation / Hibernate Validator.
You are dealing with the same issue discussed in the Validator HV-296 as well the Bean Validation BVAL-202 issue tracker.
One thing you could try is to implement a
public class NotEmptyValidator implements ConstraintValidator<NotEmpty, Iterable<String>>
You then register this custom constraint validator via validation.xml. However, this is more than just adding an annotation.
Hibernate Validator 5.2 will offer support for Java 8 type annotations. There you will be able to write:
List<#NotEmpty String> strings;
See also HV-877.

Related

Why does [Serializable] cause Newtonsoft.Json serializer to include backing fields?

If I have [Serializable] attribute on a class then it causes the resulting serialised Json string to include backing members created by the framework.
For example I get below for my Id field:
<Id>k__BackingField=20001
I could find many resources on SOF and elsewhere to get around this problem but I couldn't find why Json serializer is behaving differently when it sees [Serializable] attribute.
If the Jason serializer doesn't serialise members and only serialise properties then why does it behave differently when a class is decorated with [Serializable] attribute?
Please note I'm not looking for a way to fix this issue as I have already found that. I would like to know why Newtonsoft.Jsonserialiser behaves differently here.
In case someone wants to find the reason in the future, following explains how objects are serialised by Json.Net:
Breakdown of Type Serialization > Objects
By default a type's properties are serialized in opt-out mode. What
that means is that all public fields and properties with getters are
automatically serialized to JSON, and fields and properties that
shouldn't be serialized are opted-out by placing JsonIgnoreAttribute
on them. To serialize private members, the JsonPropertyAttribute can
be placed on private fields and properties.
Types can also be serialized using opt-in mode. Only properties and
fields that have a JsonPropertyAttribute or DataMemberAttribute on
them will be serialized. Opt-in mode for an object is specified by
placing the JsonObjectAttribute or DataContractAttribute on the type.
Finally, types can be serialized using a fields mode. All fields, both
public and private, are serialized and properties are ignored. This
can be specified by setting MemberSerialization.Fields on a type with
the JsonObjectAttribute or by using the .NET SerializableAttribute and
setting IgnoreSerializableAttribute on DefaultContractResolver to
false.

How to internationalise #Pattern(regexp="(^$|[0-9]{10})") in bean validation?

I am using bean validation to validate my entity,
it works fine according to different locales and it shows region-specific error messages, but I want to internationalize a field 'ContactNo' according to the region like my error messages #NotBlank(message="{contactNo.size}").
So how to achieve
#Pattern(regexp="(^$|[0-9]{10})")
private String contactNo;`
where the regexp value changes according to the region?
The the value for the regexp attribute has to be constant i.e. it needs to be available at compile time. So, either it needs to be a string literal as you do now or externalized into a static final variable.
I guess what you need has to be implemented in a custom Bean Validation constraint.

Override or extend serializer groups defined by annotation in Symfony2

I'm using JMS Serializer in a Symphony 2 project and I am using serializer groups defined in Annotations.
For one specific case, I would like to change or at least add one group depending on runtime parameters (i.e. checking user authorisation).
I am also using annotations to not interact directly with the serializer, my methods simply return the objects.
Is this possible? I found nothing in the documentation that makes me believe I can override the annotations.

Constraints configuring for Beans Validation via a properties file

I'd like to configure bean validation (JEE6) constraints via a properties file or database.
So for instance the Max value below would get pulled from the properties file or database.
Is this possible in ?
#Max(value = 1)
private int elvis;
Any suggestions on a possible approach.
It is not possible via standard Bean Validation. The default as per specification are annotations or as alternative XML.
In theory, Hibernate Validator has the (internal) concept of a MetaDataProvider and one could think of plugging in a DbMetaDataProvider. However, that would be quite some work and I am not sure that it would be worth the effort.
What is you use case anyways? Why don't you use XML?
You can write your own constraint and validator for that. The constraint’s argument could be some identifier of the validation parameters stored in database and the validator could query database for these parameters to validate a value according to them.
Some hints:
See this validator for an idea how to reuse existing validators from your “über validator”.
See this question and this answer for a hint how to inject bean to a validator.

Is ASP.NET MVC 1 forwards compatible with ASP.NET MVC 2?

Can I run a MVC 1 application using the MVC 2 assemblies without a hitch? I understand that some 3rd party tools have had stuff broken in MVC 2, but let's assume I'm not using those any other tools.
There have been breaking changes.
If you want a 1.0 project to run on 2.0, it does look for things in different places; so you'd have to migrate the application to 2.0..
Here are the changes that could possibly 'break' (current as of Preview 2):
Changes in Preview 2
Helpers now return an MvcHtmlString object
In order to take advantage of the new HTML-encoding expression syntax in ASP.NET 4, the return type of the HTML helpers is now MvcHtmlString instead of a string. Note that if you use ASP.NET MVC 2 and the new helpers with ASP.NET 3.5, you will not be able to take advantage of the HTML-encoding syntax; the new syntax is available only when you run ASP.NET MVC 2 on ASP.NET 4.
JsonResult now responds only to HTTP POST requests
In order to mitigate JSON hijacking attacks that have the potential for information disclosure, by default, the JsonResult class now responds only to HTTP POST requests. AJAX GET calls to action methods that return a JsonResult object should be changed to use POST instead. If necessary, you can override this behavior by setting the new JsonRequestBehavior property of JsonResult. For more information about the potential exploit, see the blog post JSON Hijacking on Phil Haack’s blog.
Model and ModelType property setters on ModelBindingContext are obsolete
A new settable ModelMetadata property has been added to the ModelBindingContext class. The new property encapsulates both the Model and the ModelType properties. Although the Model and ModelType properties are obsolete, for backward compatibility the property getters still work; they delegate to the ModelMetadata property to retrieve the value.
Changes in Preview 1
DefaultControllerFactory class changes break custom controller factories that derive from it
This change affects custom controller factories that derive from DefaultControllerFactory . The DefaultControllerFactory class was fixed by removing the RequestContext property and instead passing the request context instance to the protected virtual methods GetControllerInstance and GetControllerType.
Custom controller factories are often used to provide dependency injection for ASP.NET MVC applications.
To update the custom controller factories to support ASP.NET MVC 2, change the method signature or signatures to match the new signatures, and use the request context parameter instead of the property.
“Area” is a now a reserved route-value key
The string “area” in Route values now has special meaning in ASP.NET MVC, in the same way that “controller” and “action” do. One implication is that if HTML helpers are supplied with a route-value dictionary containing “area”, the helpers will no longer append “area” in the query string.
If you are using the Areas feature, make sure to not use {area} as part of your route URL.
Known Issues
The Add View dialog box throws a NullReferenceException when the Create strongly-typed view check box is checked, a View Content selection other than “Empty” is selected, and a View data class type name is specified for a type that does exist. When specifying a type name, either use the drop-down list to select the type name or type the fully-qualified type name. For types that do not exist, you must set View Content to “Empty”.
Check out this document. You'll learn about the breaking changes :
http://go.microsoft.com/fwlink/?LinkID=157072
One gotcha that has bitten me is that all the fields of a model are now always validated on a post.
The changes is described by Brad Wilson here.
Steve Anderson's blog post describes the issue and my favorite solution (using a custom validator).

Resources