jsf 2 spring application logging specific events - spring

I have an JSF2 app which uses Spring for transactions,security and DI container.
The application has 3 layers :
1. JSF view + JSF Managed Bean
2. Service classes
3. DAO classes
So, a request is something like:
JSF Page -> JSF MB -> Service class -> DAO Class -> DB, and the the other way around.
My problem is that there are service methods that after perform their business had to log to DB that event.
For instance, when someone activates/deactivates a user. I want to log this action along with the user id.
So, I only see two approaches here : (I`m sure there are more)
1. inside this method I determine the logged in user and perform the actual logging
- as i disadvantages here I would see the fact that this method will be not so easy to test, because of the userId picked from SpringSecurity
2. Using SpringAOP. This way would be noninvasive, which is cool, but then I would have an aspect for one method, which is not so efficient.
I would like to know if you guys had this kind of issues and if so, how did you solve them ?

Consider introducing a marker annotation. Let's call it: #LogEvent. Then annotate every method you wish to intercept. This way you can implement a single aspect with an advice that matches not on naming convention but on the presence of #LogEvent.
something like:
#After("execution(#LogEvent * *.*(..))")

Related

getting bean id of target class in advice

I have a few classes that interact with databases (more than one). Some classes are reused so for example "obs.table1" is used to interact with table1 in database "obs" while "ref.table1" is used to interact with table1 in database "ref". These databases are at different URLs and each gets its own connection pool, etc... obs.table1 and ref.table1 are both instances of MyTable1Class, defined in beans file.
I have a pointcut that intercepts calls to methods annotated with #Transactional or with a custom annotation #MyTablesAnnotation and have it set so those calls will all get routed into a #Around advice.
This all works and the flow through the advice is correct.
What I am trying to add is reporting on what is going on in there. Currently I can tell where in there I am, but I can't tell if it was obs.table1 or ref.table1 object that got me there.
Is there a way to extract the bean id of the object on whose method the advice was invoked on?
ProceedingJoinPoint that is passed to the method the only thing I do with it is call a .proceed on it and the rest is just various checks and catches. I see that I can get either the target class or proxy class out of it, but... not sure how to go from there to knowing what the bean id was.
Is it possible?
Firstly it is not recommended to depend on bean id as it creates tight coupling with framework.
To quote from docs Note that it is not usually recommended that an object depend on its bean name, as this represents a potentially brittle dependence on external configuration, as well as a possibly unnecessary dependence on a Spring API.
Now to answer your question yes it is possible to fetch the name of bean via org.springframework.beans.factory.BeanNameAware.
The class for which you require the bean name should implement it and spring will auto-magically inject the name of the bean. However there is a gotcha which you should be aware and is mentioned in docs here

Is it a good idea to use Bean Validation (JSR303) in JSF2 Webapplications?

Iam about to create a webapplication with JavaServer Faces 2. In the backend things are managed with other usual JEE technologies like EJB3.1 and JPA2. The point is, Iam following some domain driven architecture, which means, the the domain models are used at the JSF layer as backing bean models and are typically persisted as persistent entities at the persistence layer. Using the same model at different layers yields the advantage of only defining the related model restrictions once and for all. Using Bean Validation at this level provides the restrictions of this model to either JSF, JPA etc.
Now my question is, whether using bean validation with JSF2 is a good idea? My concerns are that linking the validation restrictions directly to the model might be the wrong approach, as the validation of the JSF lifecycle usually happens somehow earlier than accessing the model (for its validations rules). As much as I know JSF validation is not taking place during model processing (aka. phase 4: apply model values) but earlier in its own dedicated point in time (phase 3: process validations) and is applied on the component value (submitted value). However, how should the JSF validation (in phase 3) know the actual restrictions of the bean, if it is not validating during the model processing?
Thanks for any clarification on this.
[Edit]
To be more specific, right now Iam using Bean Validation for this purpose and it is working, as invalid values are rejected and a faces message is properly shown. I just wonder if it is the right approach, as to my understanding the validation might take place in the wrong JSF phase and thus might lead to an inconsist component model.
You can add all those bean validations in Data Transfer Object(DTO), The DTO's responsible for delevering the UI data in the JSF. After all the validations are succeed you can copy the DTO's to the Entity(Model) Object.
For copying the (DTO's to Entity) or (Entity to DTO's) we can use third party librires like dozer mapper.
This will avoid the validation restrictions directly to the model layer. I mean the Entity Objects

Application-wide process in SpringMVC

Suppose I have a certain operation that should be available to every process running in Spring MVC.
Say string normalization--
i need to run a method that normalizes the string fields before doing anything else on that form/data.
One thing specific to do is, to normalize the String fields on every input form before
they are dispatched to the back-end services. Likewise, that operation (normalization)
should be run on data from the back-end before it is dispatched to the view component.
One way of doing this that I can think of is:
Code a bean doing it-- the normalization. Then, define this bean somewhere at the top in
the context hierarchy of Spring-- ApplicationContext.xml or WebApplicationContext.xml(?),
so that it will be visible and can be used
accross all the processes/servlets in the application.
Then, Whenever and from wherever needed, invoke that method on the bean defined up there.
Or, inject it to the relevant fields in the bean definitions(?)
In this case, is there a way to call it before or during a HandlerMapping is running? if so, how?
Another i can come up with is:
Code a validator (implement Validator) to run that process and "validate" the String fields for you.
But i dont see how this would be of good help.
From what i know, a validator runs on specific object types. I can define that type generically(?)
but then I'm operating on the fields-- not objects as a whole each.
Coding validator(s) seems too costly to me for this use-- even if it is an option here.
I'm new to Spring. pls bear with me on this.

Accessing Spring Controller Name from View

With Spring, how can i retrieve the following Controller attributes in the view?
Controller name
Controller's #RequestMapping URI
Action method name
Action method's #RequestMapping URI
One approach which i have tried is by creating a subclass of HandlerInterceptorAdapter and overriding postHandle. I register my subclass as an mvc:interceptor for a list of given paths - which is clunky to maintain but was the only way to avoid my interceptor being called for ResourceHandler requests (which i don't want). In my postHandle i can easily add the 2 name attributes, but not the URIs...
Parsing from the HttpRequest object requires constraints on all Controller RequestMappings. I.e. i must always map /Controller/Action or equiv scheme. Quite limiting.
Creating an ApplicationContext and querying that with the requestURI is too long-winded.
I am thinking about dropping the HandlerInterceptorAdapter and instead defining a BaseController for all my controllers to extend.
I wanted to ask before i do this, is there a better approach?
You haven't stated why you need to do this (it sometimes helps to include your motivation, as others can suggest alternative approaches).
But I'm guessing that the Spring 3.1 features loosely termed "end point documentation" may do what you are asking... See RequestMappingHandlerMapping in the Spring documentation which doesn't provide a lot of detail, so this example project is the best place to see it in action:
Spring MVC 3.1 Demo App
example controller
example JSP page

struts2 spring jpa layers best practice

I have an app written with Struts2 Spring3 JPA2 and hibernate. In this app i have the following levels :
- struts2 actions
- spring services
- spring DAO
So, one struts action call for a service which can contain calls to one or many dao objects.
In order to display the info on the screen i have created some "mirror" objects for entities; ie: EmailMessage entity has a EmailMessageForm bean that is used to display/gather data from webforms (i don`t know if this is the best practice), and hence my problem.
In EmailMessageServiceImpl i have a method called:
public List < EmailMessage > getEmailMessages(){
//code here
}
and, if i call this from struts action i cannot get dependencies because session has expired (i have TRANSACTION entity manager). So, one solution would be to create another method
List<EmailMessageForm> getEmailMessagesForDisplay()
{
//....
}
and here to call for getEmailMessages() and convert this to form objects.
What do you recommend me ?
What is the best practice for this kind of problem ?
If by "dependencies" you mean "lazy-loaded objects", IMO it's best to get all the required data before hitting the view layer. In your current architecture it looks like that would mean a service method that retrieves the DTOs ("form beans"; I hesitate to use the term since it's easy to confuse with Struts 1).
Some say using an Open Session in View filter/interceptor is better. It's easier, but can lead to unintended consequences if the view developer isn't paying attention, including multiple N+1 queries etc.

Resources