JSF, Exception Logging using a aopalliance MethodInterceptor - jsf

I would like to log the exceptions that are thrown when serving JSF files in the same way other exceptions are logged in our web application.
We annotate classes with logged exceptions with #LoggedExceptions and a MehtodInterceptor is matched against those classes with Guice AOP (This should be very similar for other implementations of aopalliance...)
The main problem is, that the method interceptor does not work. How can i intercept method calls on JSF-backing code?

You must replace the default el-resolver (<el-resolver> in faces-context.xml) with a Guice el-resolver, so that the jsf beans become instantiated by Guide.
Search for "Guice el resolver", or take this one (I can't guarantee it works). Also check this thread.
Also, read the top results of this google search

Related

When does mojarra adds a naming container to the list of optional parameters?

In the source of the class AjaxBehaviorRenderer (line 260) there is a line that apparently appends the NamingContainer Id to the list of optional parameters of mojarra.ab(...). I've never come across it so I'm curious as to when it is used:
RenderKitUtils.appendProperty(ajaxCommand, "com.sun.faces.namingContainerId", namingContainerId, true);
line 260
While working on spec issue 790 last week, which should solve a.o. Rendering other form by ajax causes its view state to be lost, how do I add this back?, this was explained to me by Neil Griffin, a portlet guy.
It appears that portlets can have multiple JSF views rendering to the same HTML document, each with its own view state. In portlets, there's a special UIViewRoot instance which implements NamingContainer. During regular rendering, all forms, inputs and commands will have IDs and names prefixed with the view's own client ID. This will work fine during synchronous postbacks. The portlet can this way identify the exact view to restore.
However, during asynchronous postbacks, the jsf.js will create a bunch of additional ajax-specific request parameters such as javax.faces.source, javax.faces.partial.event, etc. Those request parameter names are not prefixed with the view's own client ID. Therefore the portlet cannot associate them with a specific view. Hence the impl issue 3031.
There was another problem of view state identifiers in ajax responses not being properly namespaced this way. Therefore the portlet implementation had to customize the partial response writer in the so-called "JSF bridge". This will be taken into account during implementing spec issue 790. Instead of sniffing a "portlet environment" as in current implementation, there will be checks on UIViewRoot instanceof NamingContainer which is more flexible and portlet-independent. The Mojarra-specific com.sun.faces.namingContainerId will also be removed. Instead, this value will be rendered to <partial-response id="..."> so that the jsf.js can just extract from there.
All in all, not really important if you're only targeting servlet based environments.
As per balusC comment :
It's only interesting for portlet based apps (not servlet based apps).
I can't exactly explain why and what it is used for (a portlet/liferay
guy might), but the portlet specific feature is called "namespaced
parameters". See https://web.liferay.com/web/meera.success/blog/-/blogs/liferay-requires-name-spaced-parameters

Where can I find an explanation/documentation of how each JSF component interacts with the page-lifecycle

Often when using a UI component of JSF or one of it's 3rd party component libraries, I have a hard time finding the documentation that explains where in the lifecycle the attributes of these tags will kick in.
Let's say I want to use
<h:selectOneMenu valueChangeListener="#{myBean.myMethod1}" ... />
or
<h:commandButton action="#{myBean.myMethod2}" actionListener="#{myBean.myMethod3}" ... />
Where do I find information on where in the JSF lifecycle the valueChangeListener, the action or the actionListener is called, respectively?
Please understand that these are only examples. I'm trying to avoid coming to StackOverflow for each attribute of each component when I don't understand when exactly its method will be called.
If such a documentation does not exist (??), what debugging techniques would you suggest using to figure this out on a case-by-case basis?
As to standard JSF attributes, you can find information in among others the JSF specification. The documentation states the following in chapter 2.5.1.3 about validations:
The converted value is pushed into the component's setValue() method, and a ValueChangeEvent is fired if the value has changed.
(thus, it's fired by end of conversion/validation and setting of local value)
And the following in chapter 7.3 about application actions:
An application action is an application-provided method on some Java class that performs some application-specified processing when an ActionEvent occurs, during either the Apply Request Values or the Invoke Application phase of the request processing lifecycle (depending upon the immediate property of the ActionSource instance initiating
the event).
The following related questions may also be helpful in better understanding it:
When to use valueChangeListener or f:ajax listener?
Differences between action and actionListener
As to 3rd party component libraries, look in its tag documentation or users guide. But generally they don't use custom events, but just standard JSF events or abstractions of standard ajax / HTML DOM events (which thus requires basic knowledge of ajax/HTML to start with).
As to debugging, well, easiest would be to put a breakpoint in the method being called and look in the call stack and/or the hit order. Mojarra uses for each phase a pretty self-documenting class like ProcessValidationsPhase which should clearly show up in the call stack somewhere after FacesServlet#service(). You could also log/print FacesContext#getCurrentPhaseId() or even call Thread#dumpStack() and read the stack trace in log and manually browse the associated classes.

Myfaces CODI DefaultErrorView - examples anywhere?

I've seen a reference to a DefaultErrorView in Myfaces CODI but as usual the
documentation leaves everything to the imagination. I've really found CODI to be a
great JSF addon, but it would benefit such a lot from some examples.
Probably naively I was hoping to be able to catch the dreaded ViewExpiredException
with this code:
#Page(basePath = "/defaultErrorPage.xhtml")
public final class DefaultErrorPage extends DefaultErrorView {
}
...but all that happens after session timeout is that container security takes me
to the login page when I try to issue a get request (clicking on a h:link). Does
anyone know what I can do with this DefaultErrorView, anyone got an example?
Thanks!
In the JavaDoc of DefaultErrorView you see:
...
The class which extends this class will also be used as error-view in case of security violations
(if there is no special error-view configured via
{#link org.apache.myfaces.extensions.cdi.core.api.security.Secured#errorView()})
And in the Wiki you see e.g.:
#Secured
...
In case of a violation CODI will use the DefaultErrorView as navigation target (if configured).
...
and
(Security) Error pages
The following example shows how to create a default error page. It's just allowed to provide one default error page per application.
Instead of implementing ViewConfig it's required to implement the DefaultErrorView interface.
...
as well as the manual usage:
...
this.viewNavigationHandler.navigateTo(DefaultErrorView.class);
...
The Wiki also links a nice example and there you find:
http://code.google.com/a/apache-extras.org/p/myfaces-codi-examples/source/browse/community/src/main/java/org/apache/extras/myfaces/codi/examples/community/view/config/Pages.java
-> everything is fine with the documentation ;-)

How to handle multiple submits before response is rendered?

It has been reported from testing that it is occasionally possible to press a button more than once if the response is not rendered fast enough, causing several invocations of the back-end code, which we do not want.
Application is Java EE 6 Web Profile using JSF 2.0 inside Glassfish 3.1.1.
I was wondering how this should be properly dealt with, and have thought of a few scenarios:
Submitting should disable all buttons using javascript while response is being rendered.
A flag in the Session scope saying it is already active, so the sensitive code is skipped and just moves on to the re-rendering of the response for the previous submit.
A synchronized block delaying the processing until the previous request have finished. Then it should be detected that it has been already processed and skipped.
Using one of the "new" scopes like conversion to handle the detection?
My immediate gut feeling is that the best approach is to have sensitive code blocks atomic, but then the problem is with rendering the correct response.
How should I approach this?
Submitting should disable all buttons using javascript while response is being rendered.
This is the easiest to implement in a generic manner. If you happen to use <f:ajax> exclusively, you could use the jsf.ajax.addOnEvent() to perform the job in a generic manner. An alternative JavaScript approach is to create kind of an "Loading" overlay which blocks the UI so that the enduser won't be able to interact with the underlying page anymore. This is basically an absolutely positioned hidden <div> which spans the entire viewport with some opacity (transparency). You could show it on submit and hide it on render. The keyword for this technique is "modal dialog". UI-oriented JSF component libraries have at least such a component already in their assortiment. E.g. PrimeFaces with a <p:dialog modal="true"> inside a <p:ajaxStatus>, or the <p:blockUI>
The only disadvantage is that it won't work if the client has JS disabled or don't use it and it thus won't prevent HTTP clients from double submits.
A flag in the Session scope saying it is already active, so the sensitive code is skipped and just moves on to the re-rendering of the response for the previous submit.
This is more known as "synchronizer token pattern" and has ever been requested for JSF by spec issue 559 which is currently on the ticket targeted for 2.2, but there doesn't seem to be any activity on it. The detection and blocking part is technically easy to implement, but the synchronous response handling part is not easy to implement if you want that the enduser ultimately retrieves the response as generated by the initial request. The asynchronous response handling is easy: just don't specify any components to update, i.e. empty the collection as returned by PartialViewContext#getRenderIds(). After all, this is more robust than using JS to disable the buttons or block the UI.
As far as I know, Seam 2 was the only who offered a reuseable JSF component for this, the <s:token>. I must however admit that this is an interesting idea for a new OmniFaces component. Maybe I will personally take a look at it.
A synchronized block delaying the processing until the previous request have finished. Then it should be detected that it has been already processed and skipped.
This is not easy to implement generically, this would require a change in all action methods to check if the job is already done. It also won't work if the webapp runs on multiple servers. A synchronizer token is easier as it would be performed before the action methods are invoked. A synchronizer token is also less expensive as you don't end up with multiple requests in the queue which would only cost threads/resources.
Using one of the "new" scopes like conversion to handle the detection?
This problem cannot be solved by playing around with managed bean scopes. Managed bean scopes serve a different purpose: the lifetime of the bean instance.
As Adrian mentioned, I would also use BlockUI. There is a BlockUI component from Primefaces. When you submit your forms through ajax, you could also use an overlay during the request. See Primefaces`s Ajax Status for an example.

Whats the best way of sending parameters between pages?

We are using JSF in our project (im pretty new to it) were every page have a back bean Java file.
In order to move (redirect) from one page to another, i need to put all the parameters (search criteria) in the request scope before redirecting and then retrieve it back in the next page constructor. When you have few pages deep and you want to come back to the top, it becomes really annoying to maintain.
For example, if i have page 1 with advanced search filters, which redirects to page 2, depending on the chosen item, and from page 2, you get another list were you can go to page 3 for details. Now each time i need to put all the params in the request scope/read them again, store them in hidden fields and get them back.
Whats exactly wrong with this method and whats a better way to do it in JSF?
EDIT: the environment is IBM Rational Application Developer (RAD), which have its own JSF implementation. Not sure if that makes a difference.
Putting request scoped data in session scope will bite you (very) hard if you're going to open the same page in multiple windows/tabs. Only use the session scope if the data itself is also really session scoped (excellent examples are the "logged-in user" and the "shopping cart", you want it to be exactly the same throughout the entire session). Again, don't put request scoped data in the session scope. It hurts both you and the enduser.
Just design your beans smart (it makes no sense to have different beans containing the same data) and make use of h:inputHidden where needed, if necessary in combination with managed property injection. It's indeed a bit a pain to code and maintain. You can on the other hand also just grab Tomahawk <t:saveState> if the to-be-passed data is actually as big as a "whole" managed bean. It costs only a single line in the JSF page and has always been of great assistance.
*For example, if i have page 1 with advanced search filters, which redirects to page 2, depending on the chosen item, and from page 2, you get another list were you can go to page 3 for details. Now each time i need to put all the params in the request scope/read them again, store them in hidden fields and get them back.
Whats exactly wrong with this method and whats a better way to do it in JSF?*
There's nothing wrong with this method. Maybe you coded it the wrong way which caused that it looks unnecessarily overcomplicated. I can't tell much as long as you don't post details about the code used.
As per your edit:
EDIT: the environment is IBM Rational Application Developer (RAD), which have its own JSF implementation. Not sure if that makes a difference.
This is not true. IBM doesn't have any JSF implementation. It has just a component library (the poorly maintained hx prefixed components, also known as "Faces Client Framework"). WSAD/RAD ships with Sun JSF RI (Mojarra) as standard JSF implementation, although it's usually a heavily outdated version. Ensure that you keep it updated.
I'm only starting out with JSF too to be honest, but I thought you can save managed beans in the session scope, thus being able to access the bean on each request? You can also save the state client-side avoiding nastiness about session stickyness and stuff.
So you could save the data you are currently passing as request parameters in a session-scoped managed bean, and it will be available to any requests in that user's session, destroyed when the session times out or is deliberately invalidated (say on user logout).
I don't think JSF currently supports conversation state which I think might be the exact solution to your problem, maybe a session scoped managed bean would be the pragmatic solution?
Make your managed-bean session scoped.
If you are using MyFaces you can use PageFlowScope. If using Seam then use Conversation scope.
If pageflowscope or conversation scope is not available, then use session scoped beans. In addition you can use PhaseListener to initialize or execute specific methods before the page gets called. In you case if the flow is page1 -> page2 -> page3, then initialize the session scoped bean in PhaseListener if page1 gets called.
I'll update with more info if you need.

Resources