hibernate validator: validate 2 fields match - bean-validation

I was wondering, am I overlooking something or does the hibernate validator offer no annotation to verify that 2 fields are equal (such as a password).
I know I can write my own validators, but well this seems like standard functionality.

If you’re using Spring Framework then you can use Spring Expression Language (SpEL) for that. I’ve wrote small library that provides JSR-303 validator based on SpEL that makes cross-field validations very easy. Take a look at https://github.com/jirutka/validator-spring.
This will validate equality of password fields when at least one of them is not empty.
#SpELAssert(value = "password.equals(passwordVerify)",
applyIf = "password || passwordVerify",
message = "{validator.passwords_not_same}")
public class User {
private String password;
private String passwordVerify;
}

Just went for the custom validator route. The other 2 answers here aren't really related to the question.
With a bit of googling I found a fieldmatch example.

Hibernate is a ORM Mapper.
It is used to persist data into a DB and extract it again. As such, having 2 fields with an identical value makes not much sense (From a persistance point of view). Thats something you should check in your Business logic.
And I am with Junesh... Dont persist your passwords in a retrievable format... Look up Hasing and Salting - Or even better, think about openID so you dont have to bother your clients with yet another stupid password...

I am hoping you are not saving the confirm password in the database as well. You do not have any out of the box validations for this, but instead you will have to use custom annotation which is pretty straight forward as well.

Related

How to filter in Symfony2?

First of all i am very new to Symfony 2 and started to learn.
Is there any possibility for filter a value? Perhaps filter chains too?
I know this concept from Zend Framework 1 and 2.
E.g.:
i have a string "1A- N "
now i want to filter so that only numeric values pass; result "1"
Do i have to implement this on my own i Symfony?
I would like to do something like:
$text = '1A - N';
$numberFilter = new NumberFilter();
$filteredText = $numberFilter->filter($text);
//now in $text i find '1'
But for now i nowhere found something like this in Symfony what surprises me a lot. I thought it is a full stack framework and such function is so basic.
I found something like validators but they only say if a value e.g. contains only numbers or not. Or is the validation concept of symfony like that it does not only say if it is numeric or not but filter all other smybols out, too?
Depending on what you want precisely:
disallow user input not fulfilling certain rules
use validators in forms
use asserts in entities
chenge user input in case it's wrong
use viewransformers in forms
use event listeners in forms
use event listeners for doctrine
change data that already exists in the database
use filters in twig
create a command to execute from commandline
You can also try http://php.net/manual/ro/filter.filters.sanitize.php
I have built quite big apps with Symfony and never needed such a feature. Filters are mostly used in views anyway. Symfony comes with Twig, which has filters, that can be chained, and you can write your own filters. But if you need filters in the backend to do some background processing, you can accomplish it the way you suggested.
I suggest you write an interface and use a factory pattern, so you set a standard if you make many filters, so it will be easier to make the chaining work;)
After the answers and searching i got to the following conclusion.
There is no concept for this for now in Symphony 2.
You have to write it on your own.

Does Spring MVC require copy/paste of Entity to FormObject?

I'm developing my first Spring 3 webapp. In Spring 2, we used to have formBackingObject load data from the database, then let Spring binding update some of the fields, and then onSubmit would persist those changes.
In Spring 3 it seems I have two options:
Let the user edit 100% of the persistent object. This would mean that the object's ID would need to be a hidden field
Create a form object which holds the editable data, and then map that onto the persistent object on submit
The first option is not truly an option, we cannot let the user edit all fields, and we'd rather not present data in hidden fields where anyone capable of pressing F12 can alter the values.
The second option seems like a decent design approach. However, it appears that it requires to essentially clone every editable, persistent class.
#Entity
public class Company {
private String uuid; // not editable!
.. 30 other properties, 2 are not editable
}
public class CompanyForm {
.. 28 of above properties
}
and then some mapping mechanism with lots of
public void map(CompanyForm cf, Company c) {
cf.setName(c.getName());
.. 27 other set(get())
}
I'm praying this is not the "as designed" approach of Spring's MVC binding. However, all tutorial I've found so far are terribly trivial and implement option 1 from above. Does anyone have some suggestions for implementing option 2?
Thanks, Simon
DataBinder API
Note that there are potential security implications in failing to set an array of allowed fields. In the case of HTTP form POST data for example, malicious clients can attempt to subvert an application by supplying values for fields or properties that do not exist on the form. In some cases this could lead to illegal data being set on command objects or their nested objects. For this reason, it is highly recommended to specify the allowedFields property on the DataBinder.
You can use it together with option 1
A pragmatic way would be to just ignore the non editable fields on the update statement.
I have actually circumvented this in the past by using a #ModelAttribute annotation and detecting the PK on the request, if you do it this way Spring will use the object that is returned from #ModelAttribute and automatically copy the submitted object to it.
It's kind of a hack and not obvious to someone who comes in to maintain the code though.

Keep a history of values for specific properties of EF entities

I have a requirement to keep a history of values of some fields in an EF4 ASP.NET MVC3 application. This just needs to be a log file of sorts, log the user, datetime, tablename, fieldname, oldvalue, newvalue.
Although it would be pretty easy to code this in various save routines, I'm wondering if I can get global coverage by wiring it into some sort of dataannotation, so that I can perhaps declare
[KeepHistory()]
public string Surname { get; set; }
in my partial class (I'm using POCO but generated from a T4 template).
So Questions
1) Is this a bad idea ? I'm basically proposing to side-effect changes to an entity, not directly referenced by the code, as a result of an annotation.
2) Can it be done ? Will I have access to the right context to tie up with my unit of work so that changes get saved or dropped with the context save?
3) Is there a better way?
4) If you suggest I do this, any pointers would be appreciated - everything I've read is for validation, which may not be the best starting point.
Actually, validation might be a good starting point. Since an attribute does not know about which property or class it was assigned to, but a validation-attribute gets called by the validation framework with all the necessary informátion. If you implement the System.ComponentModel.DataAnnotations.ValidationAttribute class you can override the IsValid(object, ValidationContext) method, which gives you the actual value of the property, the name of the property and the container.
This might take a lot of work, since you need to get to the currently logged-in user etc. I'm guessing that the .NET implementation provides some sort of caching for the specific attributes on an entity type, which would be a pain to implement by yourself.
Another way, would be to use the ObjectStateManager exposed by your EF ObjectContext, which can provide you with the ObjectStateEntry-objects for all entities of a given state. See the
ObjectStateManager.GetObjectStateEntries(EntityState) method, for more information about how to call it (and when). The ObjectStateEntry actually contains a record of the original and current-values, which can be compared to find any changes made within the lifetime of the current ObjectContext.
You might consider using the ObjectStateManager to inject your custom logging behavior, while this behavior decides based on property-attributes which change should be logged.

Looking for a good technique for storing email templates

I am building a site in which we are making moderate use of email templates. As in, HTML templates which we pass tokens into like {UserName}, {Email}, {NameFirst}, etc.
I am struggling with where to store these, as far as best practice goes. I'll first show the approach I took, and I'd be really excited to hear some expert perspective as a far as alternate approaches.
I created HTML templates in a folder called /Templates/.
I call a static method in my service layer, which takes in the following arguments:
UserName
UserID
Email
TemplatePath ("~/Templates")
Email Subject
Within the service layer I have my static method SendUserEmail() which makes use of a Template class - which takes a path, loads it as a string, and has a AddToken() Method.
Within my static SendUserEmail(), I build the token list off of the method signature, and send the email.
This makes for a quite long method call in my actual usage, especially since I am calling from the web.config the "TemplatePath", and "Email Subject". I could create a utility that has a shorter method call than the ConfigurationManager.AppSettings, but my concern is more that I don't usually see method signatures this long and I feel like it's because I'm doing something wrong.
This technique works great for the emails I have now, which at the most are using the first 3 tokens. However in the future I will have more tokens to pass in, and I'm just wondering what approach to take.
Do I create methods specific to the email needing to be sent? ie. SendNewUserRegistration(), SendMarketingMaterial(), and each has a different signature for the parameters?
I am using ASP.NET Membership, which contains probably the extend of all the fields I'll ever need. There are three main objects, aspnet_User, aspnet_Mebership and aspnet_profile. If it was all contained in one object, I would have just passed that in. Is there performance concerns with passing in all 3, to get all the fields I need? That is versus just passing in aspnet_User.UserID, aspnet_User.Email, etc?
I could see passing in a dictionary with the token entries, but I'm just wondering if that is too much to ask the calling page?
Is there a way to stick these in a config file of it's own called Templates.config, which has tags like -
<Templates>
<EmailTemplate Name="New User Registration">
<Tokens>
<UserName>
<UserID>
<Email>
</Tokens>
<Message Subject="Hi welcome...">
Hi {UserName}...
</Message>
</EmailTemplate>
</Templates>
I guess the main reason I'm asking, is because I'm having a hard time determining where the responsibility should be as far as determining what template to use, and how to pass in parameters. Is it OK if the calling page has to build the dictionary of TokenName, TokenValue? Or should the method take each in as a defined parameter? This looks out of place in the web.config, because I have 2 entries for and , and it feels like it should look more nested.
Thank you. Any techniques or suggestions of an objective approach I can use to ask whether my approach is OK.
First of all I would like to suggest you to use NVelocity as a template engine. As for main problem I think you can create an abstract class MailMessage and derive each one for every needed message (with unique template). So you will use this like following:
MailMessage message = new UserRegistrationMessage(tokens);
//some code that sends this message
Going this way you force each concrete XXXMessage class to be responsible for storing a template and filling it with the given tokens. How to deal with tokens? The simpliest way is to create a dictionary before passing it to the message, so each concrete message class will know how to deal with passed dictionary and what tokens it should contain, but you also need to remember what tokens it should contain. Another way (I like it more) is to create a general abstract type TokenSet and a derived one for every needed unique set of tokens. For example you can create a UserMessageTokenSet : TokenSet and several properties in it:
UserNameToken
SomeUserProfileDataToken
etc. So using this way you will always know, what data you should set for each token set and
UserRegistrationMessage will know what to take from this tokenSet.
There are a lot of ways to go. If you will describe you task better I think I will try suggest you something more concrete. But general idea is listed above. Hope it helps =)

NHibernate compromising domain objects

I'm writing an ASP.NET MVC application using NHibernate as my ORM. I'm struggling a bit with the design though, and would like some input.
So, my question is where do I put my business/validation logic (e.g., email address requires #, password >= 8 characters, etc...)?
So, which makes the most sense:
Put it on the domain objects themselves, probably in the property setters?
Introduce a service layer above my domain layer and have validators for each domain object in there?
Maintain two sets of domain objects. One dumb set for NHibernate, and another smart set for the business logic (and some sort of adapting layer in between them).
I guess my main concern with putting all the validation on the domain objects used by NHibernate. It seems inefficient to have unnecessary validation checks every time I pull objects out of the database. To be clear, I think this is a real concern since this application will be very demanding (think millions of rows in some tables).
Update:
I removed a line with incorrect information regarding NHibernate.
To clear up a couple of misconceptions:
a) NHib does not require you to map onto properties. Using access strategies you can easily map onto fields. You can also define your own custom strategy if you prefer to use something other than properties or fields.
b) If you do map onto properties, getters and setters do not need to be public. They can be protected or even private.
Having said that, I totally agree that domain object validation makes no sense when you are retrieving an entity from the database. As a result of this, I would go with services that validate data when the user attempts to update an entity.
My current project is exactly the same as yours. Using MVC for the front end and NHibernate for persistence. Currently, my validation is at a service layer(your option 2). But while I am doing the coding I am having feelings that my code is not as clean as I wish. For example
public class EntityService
{
public void SaveEntity(Entity entity)
{
if( entity.Propter1 == something )
{
throw new InvalidDataException();
}
if( entity.Propter2 == somethingElse )
{
throw new InvalidDataException();
}
...
}
}
This makes me feel that the EntityService is a "God Class". It knows way too much about Entity class and I don't like it. To me, it's feels much better to let the Entity classes to worry about themselves. But I also understand your concern of the NHibernate performance issue. So, my suggestion is to implement the validation logic in Setters and use field for NHibernate mapping.

Resources