HibernateValidator is initializing Constraints when first evaluated, not at system load time - bean-validation

We are using HibernateValidator, and have the following issue:
We create our own validator object which implements ConstraintValidator. The first time the validator validates any specific Constraint, it calls the initialization code for that constraint. This is causing a performance problem. Is there any way that we can tell HibernateValidator to run the initialization for a Constraint at load time, not the first time the Constraint is actually validated?
Thanks

There is no such way. The spec basically just says:
The life cycle of a constraint validation implementation instance is
undefined. Compliant implementations are allowed to cache
ConstraintValidator instances retrieved from the
ConstraintValidatorFactory. The initialize method is called by the
Bean validation provider prior to any use of the constraint
implementation.
It is only guaranteed that initialize is called prior a isValid call. There is no way to pre-initialize. The reason initialize is only called once is, because Validator caches the ConstraintValidator instance, but this is nothing I would rely on.
If you really want to make sure that initialize is called at startup you could do some warmup validation during this phase.
OOI, what are you doing in initialize that it becomes a performance issue?

Related

OCMock 3 Partial Mock: Class methods and the objc runtime

I'm running into an interesting issue when using OCMock 3 when partially mocking an object that defines class methods. I'm not sure if this is an issue with the dynamic subclassing that takes part as partial mocking or my misunderstanding of the objc runtime. Any help would be greatly appreciated.
As part of running tests and other debug builds we do some runtime verification of method declarations using OmniFoundations' OBRuntimeCheck. One of these checks, in short, attempts to use the runtime to verify that type signatures match for class methods across inheritance and protocol conformance. This happens by listing the classes registered in the runtime and for each class the instance methods of the metaClass are copied. For each Method from the metaClass if it exists on the metaClass's superclass the type signatures are compared.
The problem comes when calling class_getInstanceMethod on the metaClass's superclass for one of the ocmock replacement selectors, ocmock_replaced_*. The test crashes EXC_BAD_INSTRUCTION code=EXC_i386_INVOP subcode=0x0 and no class for metaclass is logged in the console. Example given:
class_getInstanceMethod(metaSuperClass, NSSelectorFromString(#"ocmock_replaced_classMessage"))
When partial mocking an object that defines a class method, it appears that the OCMock 3 framework generates a dynamic subclass, does some isa swizzling of the mocked object and also some isa swizzling of the dynamically generated class' metaClass.
This behavior and crash is new in OCMock 3 and I'm really at a loss of where to look next. Any runtime gurus have any idea what may be going on here? When looking through the code it did surprise me that the dynamically generated class used for the mock was having it's meta class swizzled out, but I don't necessarily think that is wrong. For ease in debugging I have created a simplified test case in a fresh fork of OCMock. The crashing test can be found here. Any help for guidance would be greatly appreciated.
I may be way off here, but I thought the superclass of a metaClass is NSObject (which is why you can normally call NSObject instance methods on class objects). I'm not sure you should be doing anything, normally, with the superclass of a metaClass.
In general, the metaClass stores all of the information about class methods. Therefore, getting an "instance" method on a metaClass is the same as getting a class method on the associated regular Class. The runtime can simply dereference the "isa" pointer of an instance to find a method list to find instance methods; doing the same on a Class object gets the meta class (of the same structure) and therefore the same process results in finding the class methods.
OCMock will create a magic subclass for any partial mock, and change the class on that instance to the new subclass, so all the instance method swizzling will be specific to that instance. For class methods though, I thought it had to modify the original class itself -- otherwise, calls to the regular class method in regular code would not be intercepted. It keeps a copy of the original implementation so that when you call -stopMocking on the mock it can restore the original implementation (the added ocmock_replaced* impl will still be there but should no longer be called).
You could simply ignore any selector which starts with "ocmock_replaced" since that really is not related to your actual code you are presumably checking. You might also have better luck changing "class_getInstanceMethod(metaSuperClass, ..." to "class_getClassMethod(regularSuperClass, ..."). I'm not sure why you would be getting a crash though -- I would expect class_getInstanceMethod(metaSuperClass, ...) to just return NULL in most situations.

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.

Using Doctrine 2 / DataMapper, how do I persist new entities in the domain layer?

I have a tree-like structure with a couple of entities: a process is composed of steps and a step may have sub-processes. Let's say I have 2 failure modes: abort and re-do. I have tree traversal logic implemented that cascades the fail signal up and down the tree. In the case of abort, all is well; abort cascades correctly up and down, notifying its parent and its children. In the case of re-do, the same happens, EXCEPT a new process is created to replace the one that failed. Because I'm using the DataMapper pattern, the new object can't save itself, nor is there a way to pass the new object to the EntityManager for persistence, given that entities have no knowledge of persistence or even services in general.
So, if I don't pass the EntityManager to the domain layer, how can I pick up on the creation of new objects before they go out of scope?
Would this be a good case for implementing AOP, such as with the JMSAopBundle? This is something I've read about, but haven't really found a valid use case for.
If I understand your problem correctly (your description seems to be written a bit in a hurry), I would do the following:
mark your failed nodes and your new nodes with some kind of flag (i.e. dirty flag)
Have your tree iterator count the number of failed and new nodes
Repeat tree-iteration / Re-Do prcocess as often as you want, until no more failed or new nodes are there that need to be handled
I just found a contribution from Benjamin Eberlei, regarding business logic changes in the domain layer on a more abstract level: Doctrine and Domain Events
Brief quote and summary from the blog post:
The Domain Event Pattern allows to attach events to entities and
dispatch them to event listeners only when the transaction of the
entity was successfully executed. This has several benefits over
traditional event dispatching approaches:
Puts focus on the behavior in the domain and what changes the domain triggers.
Promotes decoupling in a very simple way
No reference to the event dispatcher and all the listeners required except in the Doctrine UnitOfWork.
No need to use unexplicit Doctrine Lifecycle events that are triggered on all update operations.
Each method requiring action should:
Call a "raise" method with the event name and properties.
The "raise" method should create a new DomainEvent object and set it into an events array stored in the entity in memory.
An event listener should listen to Doctrine lifecycle events (e.g. postInsert), keeping entities in memory that (a) implement events, and (b) have events to process.
This event listener should dispatch a new (custom) event in the preFlush/postFlush callback containing the entity of interest and any relevant information.
A second event listener should listen for these custom events and trigger the logic necessary (e.g. onNewEntityAddedToTree)
I have not implemented this yet, but it sounds like it should accomplish exactly what I'm looking for in a more automated fashion that the method I actually implemented.

Asp.net: Can a delegate ("Action") be serialized into control state?

I am implementing a user control that has a method that takes an Action delegate as a parm.
Attempting to store the delegate in Control State yields a serialization error. Is it even possible to serialize a delegate into Control State?
BP
Not easily - and it could open the door for potential problems.
It is theoretically possible to use reflection to determine which method of an object the delegate is invoking, and write a custom serialization process for it. Upon deserialization you would once again need to write logic to convert the information into a delegate reference.
The problem is that in the general case, discovering the object at runtime that you need to re-generate the delegate for is not always possible. If the delegate refers to a lambda or anonymous method that complicates things even more because their may be closures involved.
You are probably better off either:
Not preserving the Action delegate between requests and having the ASP.NET code re-attach the delegate on postback. This is the least risky option IMHO.
Storing the delegate reference in session state and reattach it to the deserialized object on postback. This option is risky for two reasons:
a) holding on to object references indefinitely in memory if the end user never posts back, or you forget to clear the object from server state.
b) if the delegate references page elements (controls, etc) you may run
into subtle bugs because the delegate will operate against the objects from the previous request, and not the new request.
In this post the author serializes an Action object to be executed later in time.
You can extend at your own action serializing to a string instead to a file.
Very interesting:
http://mikehadlow.blogspot.com/2011/04/serializing-continuations.html

Calling a getter without assigning it to anything (lazy loading)

I have a DTO which can be fully loaded or lazy loaded using Lazy Load Pattern. How it is loaded depends on what the Flex Application needs. However, this DTO will be sent to a Flex application (swf). Normally, a collection for instance, will only be loaded when called. In my case however, the collection will only be called in Flex, so my implementation on the .NET side will obviously not work in this case (except if Flex would do a server call... something I would like to avoid).
In the getter of the collection, the data is retrieved from the database. If I would be working with ASP.NET pages, it would work, but not if the DTO is sent to Flex.
How would you deal with this? I could call the getter before sending the DTO to Flex, but that seems awful... + calling the getter can only be done if it is assigned to something (and the local variable that will hold the collection will never be used...).
You can introduce a method to load dependents - loadDependencies - that should take of all lazy loading for your DTO object before being sent over the wire (to Flex). You can abstract this method to an interface to streamline such process across different DTOs. There is nothing against using getters the way you described it inside this method.
I would probably introduce a Finalize method for the class and perhaps a FinalizeAll extension method for various collections of the class. This method would simply go through and reference all the getters on the public properties of the class to ensure that they are loaded. You would invoke Finalize (or FinalizeAll) before sending the object(s) to your Flex app. You might even want to make this an interface so that you can test for the need for finalization before transfering your objects and invoke the method based on a test for the interface rather than checking for each class individually.
NOTE: Finalize is just the first name that popped into mind. There may be (probably is) a better name for this.

Resources